当使用ADO来读写Excel工作簿时,我们可能会遇到最后一个单元格头没有被复制的问题。这通常是由于Excel工作簿的结构不同于标准工作簿而导致的。为了解决这个问题,我们可以使用以下代码来从Excel工作簿中读取数据:
Dim cn As Object, rs As Object, output As String, sql As String
Dim shtName As String, wbPath As String, i As Integer, lastCol As Integer
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
wbPath = "C:\Users\username\Documents\Test.xlsx"
shtName = "Sheet1"
lastCol = 0
' Open the connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & wbPath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
' Get column count
sql = "SELECT COUNT(*) FROM [" & shtName & "$]"
Set rs = cn.Execute(sql)
lastCol = rs.Fields(0).Value
' Fetch data
sql = "SELECT * FROM [" & shtName & "$A1:" & Chr(64 + lastCol) & "100]"
Set rs = cn.Execute(sql)
' Process data
Do While Not rs.EOF
For i = 0 To lastCol - 1
output = output & rs.Fields(i).Value & vbTab
Next i
output = output & vbCrLf
rs.MoveNext
Loop
' Close the connection
rs.Close
cn.Close
' Output data
Debug.Print output
在这段代码中,我们首先获取了列的数量,并根据数量的值来构造SQL语句来获取所有单元格的值。然后我们遍历了所有数据并将它们作为字符串输出。
通过这种方式,我们可以避免忽略最后一个单元格头的问题,为使用ADO读写Excel工作