mysql - 在 Mac Excel 2011 中从 Mysql DB 获取数据的 VBA 代码

标签 mysql excel vba macos osx-mountain-lion

我在 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/

相关文章:

vba - Excel VBA 公式作为文本问题

excel - 使用不带变量的公式填充列

sql-server - 如何从 SQL Server 存储过程返回值并在 Access VBA 中使用它们

excel - 忽略 "subscript out of range"错误一次,处理第一次迭代

vba - 尝试添加随机整数的总和,VBA

php - Android PHP 查询不起作用

php - 如何比较两个值?

php - 在一个查询中连接/查看 Mysql 三个表

jquery - 使用 JQuery 更改 mysql 数据库中的第二个下拉选择框

excel - 为 Excel 中的所有单元格添加公共(public)前缀