ADODB を使用してコードですべてを実行してみてください。
まず、各シートで、セル A1 (おそらく) に新しい名前付き範囲を作成します。
"クエリ" & xsheet.name
そのセルに、そのシートに固有のクエリを入力します
次に、VBA コード モジュールで次のコードを使用します。
sub getData()
dim cn as new adodb.connection
dim rs as new adodb.recordset
dim connStr as string ' connection string
dim sUDLFile as string ' path and name of Microsoft Data Link File (UDL FILE)
dim xSheet as worksheet
connStr="File Name=" & sUDLFile
cn.open connstr
'loop through all the worksheets
for each xSheet in thisworkbook.worksheets
with rs
' open the connection to the db...
.activeconnection=cn
'get the query from the range on the worksheet!
sQry=xsheet.range("Query" & xsheet.name).text
' open the query from the DB
.open sQry
' dump the dataset onto the worksheet with one line of code in B5 cell!
xsheet.range(B5).copyfromrecordset rs
.close
end with
next
' clean up and release memory
cn.close
set cn=nothing
set rs=nothing
'
end sub
MS Windows Explorer で接続文字列 (UDL FILE) を作成するには:
- ワークブックがあるディレクトリに移動します
- 右クリックして [新規...] > [Microsoft データ リンク] を選択します。
- 名前を適切なものに変更します (name.udl など)。
- 新しいファイルをダブルクリックし、データベースへの接続を作成してテストするように設定します
何か問題があれば、お尋ねください!
フィリップ