我很适合尝试弄清楚如何将Excel电子表格中的记录读取到Word文档中。我正在使用Office365。我发现一些文章使我与工作簿和工作表建立了联系,但未返回任何记录。 我引用了ActiveX数据对象2.8库 当代码到达消息框时,它返回-1
有帮助吗?我想念什么?
这是我现在要编写的代码。
Sub CreateLetter()
Dim rs As ADODB.Recordset, rsCount As ADODB.Recordset
Dim cn As ADODB.Connection
Dim sqlGetTbl As String
Dim sDataSource As String, sDataTable As String
Dim sProvider As String
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
sDataSource = "D:\spreadsheetname.xlsx"
sDataTable = "[Donor Contact List$]"
sProvider = "Microsoft.ACE.OLEDB.16.0;"
sDataSource = sDataSource & ";Extended Properties = 'Excel 12.0 Xml;HDR=Yes';"
With cn
.Provider = sProvider
.ConnectionString = "Data Source=" & sDataSource
.Open
End With
sqlGetTbl = "SELECT * FROM " & sDataTable
Set rs = cn.Execute(sqlGetTbl)
MsgBox rs.RecordCount
Do
With Selection
.TypeText FullName & Chr(11) & Street & Chr(11) & City & ", " & St & " " & Zip
.TypeParagraph
End With
Loop Until rs.EOF
rs.Close
cn.Close
Set cn = Nothing
Set rs = Nothing
结束子
答案 0 :(得分:1)
以下对我有用。在我使用的测试数据源中获取记录集信息的关键是在连接字符串中包含IMEX=1
,以便指定数据源具有标头。
问题中的代码还有其他问题:
rs.MoveFirst
来“初始化”记录集(将其保存到第一条记录中。rs.MoveNext
,否则代码将“卡在”第一个记录上并进入无限循环。Do While Not rs.EOF
进行退出循环的测试更为安全。Nothing
)。在释放记录集之前不可能释放连接-活动记录集将使连接保持“活动”状态。我的示例代码:
Sub CreateLetter()
Dim rs As ADODB.Recordset, rsCount As ADODB.Recordset
Dim cn As ADODB.Connection
Dim sqlGetTbl As String
Dim sDataSource As String, sDataTable As String
Dim sProvider As String
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
sDataSource = "D:\spreadsheetname.xlsx"
sDataTable = "[Donor Contact List$]"
sProvider = "Microsoft.ACE.OLEDB.16.0;"
sDataSource = sDataSource & ";Extended Properties = 'Excel 12.0 Xml;HDR=Yes;IMEX=1';"
With cn
.Provider = sProvider
.ConnectionString = "Data Source=" & sDataSource
.Open
End With
sqlGetTbl = "SELECT * FROM " & sDataTable
cn.CursorLocation = adUseClient
Set rs = cn.Execute(sqlGetTbl)
MsgBox rs.RecordCount
rs.MoveFirst
Do While Not rs.EOF
With Selection
.TypeText rs.Fields("Fullname").value & Chr(11) & rs.Fields("street").value & Chr(11) & rs.Fields("city").value & ", " & st & " " & rs.Fields("Zip").Value
.TypeParagraph
End With
rs.MoveNext
Loop
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub