|
QueryTable を新規に作成する場合。 VBA を使用して、外部データを Excel 97 のワークシートに取り込むには、Add メソッドを使用します。 このメソッドにより作成したクエリーは、Refresh メソッドが呼び出されるまで実行されません。 この構文は、以下のとおりです。 WorkSheets オブジェクト .QueryTables.Add(Connection, Destination, Sql)例えば、テーブル Test からフィールド Field1 と Field2 を抽出する QueryTable を新規に作成し、 抽出結果を Sheet1 のセル A1 に返すには、次のように記述します。 With Sheet1.QueryTables.Add(Connection:= _
"ODBC;DSN=SQLSrv65;UID=demo;PWD=password", _
Destination:=Range("A1"))
.Sql = Array("SELECT Test.Field1, Test.Field2 FROM Test")
.Name = "Contact List"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
実務編
Application.DisplayAlerts = False
With Sheets("Sheet2").QueryTables.Add(Connection:= _
"ODBC;DSN=" & UDB_DB & ";UID=" & "" & ";PWD=" & "", Destination:=Range("Sheet2!B11"))
.SQL = Array(SQL)
.FieldNames = False
.RefreshStyle = xlOverwriteCells
.Refresh BackgroundQuery:=False
Dim er
If Application.ODBCErrors.Count > 0 Then
Set er = Application.ODBCErrors(1)
msg = MsgBox("エラー発生が発生しました:" & _
er.ErrorString & " : " & er.SqlState, vbOKOnly + vbCritical, Title:="エラーが発生しました")
Else
'MsgBox "クエリー完了。: すべてのレコードが返されました。"
End If
Set er = Nothing
End With
Application.DisplayAlerts = True
|
||||