Excel中VBA 连接 数据库 方法- 摘自网络
Sub GetData() Dim strConn As String, strSQL As String Dim conn As ADODB.Connection Dim ds As ADODB.Recordset Dim col As Integer '清空电子表格的所有数据 Cells.Clear '连接数据库的字符串 strConn = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=name;Password=pwd;Initial Catalog=dataname;Data Source=servername" '查询语句 strSQL = "select * from table1" Set conn = New ADODB.Connection Set ds = New ADODB.Recordset '打开数据库连接 conn.Open strConn With ds '根据查询语句获得数据 .Open strSQL, conn '自动控制加入所有列标题 For col = 0 To ds.Fields.Count - 1 '请注意Offset(0, col)中的参数一定要正确噢 Range("A1").Offset(0, col).Value = ds.Fields(col).Name Next '加入所有行数据 Range("a1").Offset(1, 0).CopyFromRecordset ds End With '以下是关闭数据库连接和清空资源 Set ds = Nothing conn.Close Set conn = Nothing End Sub
注意:
1. 保存时您可能看到以下消息:“Privacy warning:This document contains macros, ActiveX Controls, XML expansion pack...”
解决方法:
要取消该警告,回到当前Excel-> Options -> Trust Center -> Trust Center Settings...-> Privacy Options,取消选中“Remove Personal information from file properties on save”复选框。
2. 保存时您可能看到以下消息:“
the following features cannot be saved in macro-free workbooks
vb project
to save a file with these features click no and then choose a macro-enabled file type in the file type list.
to continue saving as a macro-free workbook, click yes"
解决方法:
1. 你所打开的文件是只读的
2. 你所打开的文件是未启用宏的工作薄xlsx,而你使用了宏,所以提示需要你保存为xlsm