mysql - 使用 VBA 将 mySQL 数据库中的值提取到 Excel 中

标签 mysql excel vba

我已在计算机上安装了 mySQL 服务器,并创建了名为 Sales 的数据库,其中包含一个名为 Orders 的表。您还可以在 SQL fiddle here 中找到该表。 :

CREATE TABLE Orders (
    OrderID INT,
    Customer VARCHAR(255),
    Revenue VARCHAR(255)
);

INSERT INTO Orders
(OrderID, Customer, Revenue)
VALUES 
("1", "Customer A","400"),
("2", "Customer A","200"),
("3", "Customer B","600"),
("4", "Customer C","150"),
("5", "Customer C","800"),
("6", "Customer C","300");

然后我创建了一个 Excel 文件并激活了 Microsoft ActiveX Data Objects 2.8 Library
现在我想连接到上面的数据库并使用以下 VBA 脚本从中提取数据:

Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"

Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
Sheet1.Range("A1").Value = rs

End Sub

但是,当我运行此 VBA 时,我收到运行时错误 3704。据我所知,这个错误可能是由这些行引起的:

Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")

因为如果我删除它们,VBA 运行时不会出现错误。

我需要对代码进行哪些更改才能从 mySQL 数据库中提取数据?

最佳答案

您的连接未打开

试试这个

    Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
conn.open
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
Sheet1.Range("A1").Value = rs

End Sub

关于mysql - 使用 VBA 将 mySQL 数据库中的值提取到 Excel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57942612/

相关文章:

mysql - 如何为没有内容的行打印零?

excel - 多个工作表更改公式 - 在下拉列表中选择某些条件时的多个操作

vba - 在 Excel 中使用宏在循环中查找和替换

excel - 如何有条件地填充列

mysql - Excel-Vba 连接 Mysql localhost 失败

php - 如果所有三个字段都是 'Yes',则 SQL 隐藏结果

python - 时间戳值改变 Django

mysql - 全文匹配()反对()返回空集

c# - 使用 OleDB 读取范围 Excel 工作表

vba - Excel 宏 - 逗号分隔的单元格到行保留/聚合列