Sub ExcelにSQLをかける()
Dim adoCN As Object
Dim adoRS As Object
Dim strBookPath As String
Dim wb As Workbook
Dim lastRow As Long
Dim arMaster As Variant
Dim arKeySet As Variant
Dim i As Long
Dim str_条件1 As String
Dim str_条件2 As String
Dim str_SQL As String
Set adoCN = CreateObject("ADODB.Connection")
Set adoRS = CreateObject("ADODB.Recordset")
With Sheets("マスタ")
lastRow = .Cells(Rows.Count, 1).End(xlUp).Row
arMaster = .Range(Cells(2, 1), Cells(lastRow, 2))
End With
strBookPath = "C:\Users\デスクトップ\ExcelVBAプロジェクト\SQLをかける\test.xlsx"
Set wb = Workbooks.Open(strBookPath)
adoCN.Open = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strBookPath & ";" & _
"Extended Properties='Excel 12.0;HDR=YES'"
For i = 1 To UBound(arMaster) Step 2
arKeySet = fncGetMaster(arMaster, i)
str_条件1 = arKeySet(0)
str_条件2 = arKeySet(1)
str_SQL = "SELECT * FROM [Sheet1$] WHERE 購入品名 IN('" & str_条件1 & "','" & str_条件2 & "') ORDER BY 単価"
Debug.Print str_SQL
Set adoRS = adoCN.Execute(str_SQL)
wb.Sheets("Sheet2").Select
If i = 1 Then
lastRow = 2
Else
lastRow = wb.Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
End If
wb.Sheets("Sheet2").Select
wb.Sheets("Sheet2").Range("A" & CStr(lastRow + 1)).CopyFromRecordset Data:=adoRS
adoRS.Close
Set adoRS = Nothing
Next
wb.Save
wb.Close True
adoRS.Close: adoCN.Close
Set adoRS = Nothing: Set adoCN = Nothing
End Sub
Function fncGetMaster(arr As Variant, intNum As Long) As Variant
Dim i As Long
Dim j As Integer
Dim strTemp As String
Dim result(1) As String
i = 1
j = 0
For i = intNum To intNum + 1
strTemp = arr(i, 1)
result(j) = strTemp
j = j + 1
Next
fncGetMaster = result
End Function