来自EXCEL VBA的MYSQL查询基于单元格内容

时间:2011-08-06 08:22:21

标签: mysql excel excel-vba vba

我试图通过VBA从EXCEL执行简单查询。我希望根据A2单元格的值,查询应该执行。我正在努力实现这一目标,但需要起诉帮助。 连接:

conMySQL.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver};" & "SERVER=" & server & ";" & " DATABASE=" & database & ";" & "UID=" & login_user & ";PWD=" & password & "; OPTION=3; PORT=" & port & ";Connect Timeout=20;"

'open the connection
conMySQL.Open

然后查询:

strSQL = "SELECT x FROM some_table"; x = A2's value
MySQL.Query (strSQL)

With rsTemporary
      Do Until .EOF
          recordCount = recordCount + 1
          some_variable = ![supcode]
          rsTemporary.MoveNext
      Loop
End With
        MySQL.closeCon

1 个答案:

答案 0 :(得分:1)

如果您的主要问题是如何在查询中将单元格A2中的值作为列名称,则应替换该行。

strSQL = "SELECT " & Cells(2, 1).Value & " FROM some_table"

或者x是包含单元格A2中的值的现有变量:

strSQL = "SELECT " & x & " FROM some_table"