我在 Windows 中使用 ADODB 代码从 Mysql 数据库中获取数据并且工作正常。但是,我似乎无法让我的 Excel 工作簿(使用 ADODB)与 Excel Mac 2011 一起工作。经过大量谷歌搜索,我从 Actual tech 找到了一个 ODBC 连接器,我能够使用 Microsoft Query 获取三行。但我希望使用 VBA 代码完成此操作,但一直无法这样做。有没有人让这个工作?如果是的话,你能给我一个示例代码吗?提前致谢!!
P.S:我知道有一个类似的现有问题,但答案中提供的链接不再有效。因此,我提出了一个新问题
此外,如果有人需要链接以通过 Microsoft Query 进行操作,请使用以下链接: http://www.agentjim.com/MVP/Excel/2011Relational7Queries.html
这是我在 Windows 中使用的代码:
Sub getMysqlDBdata()
Dim Cn As Object
Dim sqlQa as string
dim temparray1 as variant
Source = "MySQL"
mysql_driver = "MySQL ODBC 5.2 ANSI Driver"
sqlQa = "select * from test.TestTable;"
Set Cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
Cn.Open "Driver={" & "MySQL ODBC 5.2 ANSI Driver" & "};Server=" & "127.0.01" & ";Database= test;UID=" & "root" & ";PWD=" & "12345"
rs.Open sqlQa, Cn, adOpenStatic
temparray1 = rs.GetRows()
rs.Close
Set rs = Nothing
End Sub
最佳答案
经过大量谷歌搜索后,我发现了 Bryan Duchesne 提供的示例代码在 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
关于mysql - 在 Mac Excel 2011 中从 Mysql DB 获取数据的 VBA 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22433645/