銀河鉄道

【VBA】Excelシート内の表データをSQLで操作したい

サムネイル
Excel内でSQLを使いたい

Excelシートを、FROMに指定することができる

標準モジュールに記述

[シート名$]には、指定シートのシート名を “” 無しで記述

Public Sub test()
    Dim bookPath As String: bookPath = "(Excelファイルのフルパスを指定)"
    
    Dim cn As Object: Set cn = CreateObject("ADODB.Connection")
    Dim rs As Object: Set rs = CreateObject("ADODB.Recordset")
    
    Dim tbl As String
    Dim select_ As String
    Dim where_ As String
    
    tbl = " " & "[シート名$]" & " "
    select_ = " " & "aaa, bbb, ccc" & " "
    where_ = " " & "ccc > 0" & " " '0以外の値を抽出する場合

    Dim strSQL As String
    strSQL = _
            "SELECT" & select_ & _
            "FROM" & tbl & _
            "WHERE" & where_

    '接続
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .Properties("Extended Properties") = "Excel 12.0"
        .Open bookPath
    End With
    
    'レコードセット
    Dim ary As Variant
    With rs
        .Open strSQL, cn
        
        'データを配列に入れる
        ary = .GetRows
        
        '※配列ではなく、シートに貼り付けたい場合
        'Sheet1.Cells(1, 1).CopyFromRecordset rs
        
        .Close
    End With
    
    cn.Close
    
    Set rs = Nothing
    Set cn = Nothing
End Sub

データベースに移行したくなったときのためにも、便利かも

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧