我想通过Excel VBA读取Access表,并打印每一行每一列的内容。
到目前为止,我有以下代码,但它只会打印第一行的内容。如何使其打印所有行?
我的测试表有2列(因此For i= 0 to 1
)和4行,但是实际上我可能会有可变数量的列和行,因此最好用代码来覆盖。
Sub get_column()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim i As Long
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=M:\test_database.accdb;" '& _
'"User Id=admin;Password=admin"
strSql = "SELECT Table1.CC_Number, Table1.Region FROM Table1;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
For i = 0 To 1
Debug.Print rs.Fields(i)
Next i
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
答案 0 :(得分:1)
您可以轻松地遍历所有字段,并使用.MoveNext
和.EOF
打印所有行:
Set rs = cn.Execute(strSql)
Dim fld As Object
Do While Not rs.EOF
For Each fld In rs.Fields
Debug.Print fld.Name; vbTab; fld.Value
Next
Debug.Print "" 'Blank line between records
rs.MoveNext
Loop
rs.Close