我有一个VBA脚本,但是我收到错误“编译错误:需要对象”
我在单词VBA中添加了以下引用以供应用,但它没有帮助
-Visual Basic For Applications
-Microsoft Word 12.0 Object library
-OLE Automation
-Microsoft office 12.0 Object Library
-Microsoft ActiveX data Objects 2.8 Library
-Microsoft ActiveX data Objects Recordset 2.8 Library
-Microsoft remote Data Services 2.7 Library
此脚本中缺少什么?
===========================
Sub ftbox()
Dim spinr As String
Dim cnn As ADODB.Connection
Set cnn = New ADODB.Connection
cnn.Open "lv", "xx", "xxxxxx"
Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormField("custid").Result)
ActiveDocument.FormFields("reg").Result = spinr
End Sub
答案 0 :(得分:0)
我认为您收到错误是因为:
Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormField("custid").Result)
应该是:
Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormFields("custid").Result)
话虽如此,你的代码中似乎有很多奇怪的东西。这样:
cnn.Open "lv", "xx", "xxxxxx"
对我来说很奇怪。我不确定您要连接的数据源是什么(除非您只是为了发布而这样做)。也:
Dim spinr As String
...
Set spinr = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormField("custid").Result)
cnn.Execute返回的对象是ADODB.Recordset,而不是字符串。 spinr应该是ADODB.Recordset类型。
最后:
ActiveDocument.FormFields("reg").Result = spinr
应该更像:
ActiveDocument.FormFields("reg").Result = spinr.Fields("spinnr")
因为spinnr将是一个Recordset对象。您不会关闭连接或取消分配对象。如果您尝试连接到数据源,可能会导致问题,特别是如果代码中断并且您结束该过程。我不太了解Word对象,所以你可能会遇到更多问题。
答案 1 :(得分:0)
我尝试使用您的代码并得到了同样的错误。我认为错误正在发生,因为您正在使用SET预先修复字符串(赋值)。如果删除SET,则会出现其他错误。
如前所述,您需要使用记录集:
Dim rst as ADODB.Recordset
然后在打开连接后运行以下2行:
Set rst = cnn.Execute("select spinnr from cust where custid=" & ActiveDocument.FormFields("custid").Result)
spinr = rst.GetString(adClipString, -1, vbTab)
我希望这会有所帮助。