我根据本书的说明编写了第一个ADO / SQL数据提取代码。
数据库具有用户名和密码,但是这里没有用户名和密码输入。
Sub GetAccessData_With_SQL()
'step 1 Declare your variables
Dim MyConnect As String
Dim MyRS As ADODB.Recordset
Dim MySQL As String
'step 2 Declare your connnection string
MyConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = C:\Thorsys\TAS.accdb"
'step 3 Build your SQL statement
MySQL = "SELECT productID, headID, list FROM dbo_tblSTproduct"
'step 4 Instantiate and specify your recordset
Set MyRS = New ADODB.Recordset
MyRS.Open MySQL, MyConnect, adOpenStatic, adLockReadOnly
'step 5 Copy the recordset to Excel
Sheets("ADO and SQL").Select
ActiveSheet.Range("A2").CopyFromRecordset MyRS
'step 6 Add column labels
With ActiveSheet.Range("A1:E1")
.Value = Array("productID", "headID", "list")
.EntireColumn.AutoFit
End With
End Sub
您必须在连接字符串中输入用户名和密码...示例:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Thorsys\TAS.accdb;User ID=myUsername;Password=myPassword;