dbPath = "C:\path\to\your\database.accdb"
strSQL = Replace(strSQL, "*", "%")
Sub GetAccessData_Pro_Version()
Dim conn As Object, rs As Object
Dim strSQL As String, rawSQL As String
Dim dbPath As String, ws As Worksheet
Dim lines() As String, i As Long, cleanSQL As String
' --- 設定エリア ---
Set ws = ThisWorkbook.Sheets("Sheet1")
dbPath = "C:\path\to\your\database.accdb" ' ★実際のパスに変更
' ------------------
' 1. テキストボックスからSQLを読み込む
On Error Resume Next
rawSQL = ws.Shapes("テキスト ボックス 1").TextFrame2.TextRange.Characters.Text
On Error GoTo 0
If Trim(rawSQL) = "" Then
MsgBox "テキストボックスにSQLを入力してください。", vbExclamation
Exit Sub
End If
' 2. 【お掃除機能】コメント行(--)の除去と整形
lines = Split(rawSQL, vbCr) ' 改行で分割
cleanSQL = ""
For i = 0 To UBound(lines)
Dim currentLine As String
currentLine = Replace(lines(i), vbLf, "") ' 残った改行コードを除去
' 「--」があれば、それ以降をカット
If InStr(currentLine, "--") > 0 Then
currentLine = Left(currentLine, InStr(currentLine, "--") - 1)
End If
' 空行でなければ連結(前後にスペースをいれて結合ミスを防ぐ)
If Trim(currentLine) <> "" Then
cleanSQL = cleanSQL & " " & currentLine
End If
Next i
' 3. 【自動変換】Access記号をVBA(ADO)用に変換
strSQL = cleanSQL
strSQL = Replace(strSQL, "*", "%") ' あいまい検索
strSQL = Replace(strSQL, "*", "%")
strSQL = Replace(strSQL, "?", "_") ' 1文字検索
strSQL = Replace(strSQL, "?", "_")
' 4. ADO接続と実行
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
On Error Resume Next
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath & ";"
If Err.Number <> 0 Then
MsgBox "DB接続エラー: " & Err.Description, vbCritical
Exit Sub
End If
rs.Open strSQL, conn, 3, 1
If Err.Number <> 0 Then
MsgBox "SQL実行エラーです。構文や項目名を確認してください。" & vbCrLf & _
"内容: " & Err.Description, vbCritical
GoTo CleanUp
End If
On Error GoTo 0
' 5. 書き出し処理
Application.ScreenUpdating = False
ws.Cells.Clear
' 見出し書き出し
For i = 0 To rs.Fields.Count - 1
ws.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
' データ流し込み
If Not rs.EOF Then
ws.Cells(2, 1).CopyFromRecordset rs
ws.Columns.AutoFit
Else
MsgBox "条件に一致するデータは見つかりませんでした。", vbInformation
End If
CleanUp:
If rs.State <> 0 Then rs.Close
conn.Close
Set rs = Nothing: Set conn = Nothing
Application.ScreenUpdating = True
End Sub