我正在尝试基于Excel工作簿Sheet1中单元格A2的值,向查询编辑器中的以下MySQL查询添加变量值:
SELECT o.Name, o.OrganizationId
FROM Organization AS o
WHERE o.OrganizationId = Sheet1!A2
ORDER BY o.Name ASC
我尝试使用Customized Parameter,但它似乎不适用于MySQL查询。
我尝试通过VBA脚本运行查询的另一件事:
Sub VoucherQuery()
queryString = "SELECT Name, OrganizationId FROM [Vouchers!$A1:B1000000]
WHERE OrganizationId=" & Worksheets("Sheet1").Range("A2").Value
End Sub
但是无法将其与a query I looked up结合使用。
最后一次尝试是让我创建一个新的工作簿并从工作簿获取数据,在这里我使用原始SQL查询(与上述查询相同,但没有WHERE子句)从工作簿中提取数据,并尝试添加条件,但是我找不到用于提取数据的任何代码进行编辑。
有人知道如何使用Excel中的“获取数据”->“从MySQL数据库查询编辑器”来实现这一目标吗?
答案 0 :(得分:0)
不确定查询编辑器,但是此宏适合您的情况。
只需要在注释"fill these out below"
下填写您的连接信息,并将schema
替换为查询字符串中的实际架构即可。
Sub SendQuery()
Dim conn As Object
Dim rs1 As Object
Dim sqlstr As String
Dim val, server_name, database_name, user_id, password As String
Set conn = CreateObject("ADODB.Connection")
Set rs1 = CreateObject("ADODB.Recordset")
val = Trim(CStr(ThisWorkbook.Worksheets("Sheet1").Range("A2").Value))
' fill these out below
server_name = ""
database_name = ""
user_id = ""
password = ""
' connect to database
conn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=3"
' setup select string
sqlstr = "SELECT o.Name, o.OrganizationId FROM schema.Organization As o WHERE o.OrganizationId = '" & val & "' ORDER BY o.Name ASC"
' send query
rs1.Open sqlstr, conn, adOpenStatic
' copy data to sheet
With ThisWorkbook.Worksheets("Sheet1").Cells(1, 1)
.ClearContents
.CopyFromRecordset rs1
End With
' cleanup
rs1.Close
Set rs1 = Nothing
End Sub