1. 程式人生 > >EXCEL-VBA:通過SQL查詢資料Sheet中的資料

EXCEL-VBA:通過SQL查詢資料Sheet中的資料

Sub RunCode()
    Dim ConnStr As String
    ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=yes';Data Source =" & ThisWorkbook.FullName    '//需OFFICE 2007及以上版本
    Set conn = CreateObject("adodb.connection")
    conn.Open ConnStr
    
    Sql = "select * from [Sheet1$] AS A"
    Sql = Sql + " Left Join [Sheet2$] AS B ON A.條碼=B.條碼"
    Set rs = conn.Execute(Sql)
    
    Sheets("Sheet3").Select
    Sheets("Sheet3").Cells.Clear
    Range("A1").CopyFromRecordset rs '將結果可以放到單元格內
End Sub