VBA code to fetch data from Mysql DB in Mac Excel 2011

前端 未结 1 1678
我在风中等你
我在风中等你 2021-01-06 09:17

I was using ADODB code in Windows to fetch data from Mysql Database and it was working fine. However, I can not seem to get my Excel workbook (using ADODB) to work with Exce

相关标签:
1条回答
  • 2021-01-06 10:04

    After a lot of googling I came across this sample code provided by Bryan Duchesne in MSDN:

    Sub TestSqlConnection()
    Dim sqlstring As String
    Dim connstring As String
    Dim sLogin As String
    sLogon = "Uid=myUserID;Pwd=myPassowrkd;"
    sqlstring = "select * from zitemloc"
    connstring = "ODBC;DSN=myDSN;" & sLogon
    ActiveSheet.Range("B1:t2000").Clear
    
    Dim qt As QueryTable
    For Each qt In ActiveSheet.QueryTables
        qt.Delete
    Next qt
    With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("B1"),   Sql:=sqlstring)
        .BackgroundQuery = False
        .Refresh
    End With
    
    Set qt = ActiveSheet.QueryTables(1)
    Dim rowCount As Integer
    rowCount = UBound(qt.ResultRange.Value)
    
    
    Dim ix, iy As Integer
    Dim data As Variant
    Dim colCount As Integer
    colCount = qt.ResultRange.Columns.Count
    
    For ix = 1 To rowCount
        If Not IsArray(data) Then
                ReDim data(rowCount - 1, colCount - 1)
        End If
        For iy = 1 To qt.ResultRange.Columns.Count
            data(ix - 1, iy - 1) = qt.ResultRange.Value2(ix, iy)
    
        Next
    Next
    End Sub
    
    0 讨论(0)
提交回复
热议问题