我正在尝试使用宏来生成发票编号,然后将其插入特定位置,然后将文档另存为新生成的编号。我有下面的代码,但是当我尝试运行它时,它会返回一个错误,表示"集合中请求的成员不存在。"
Sub CreateInvoiceNumber()
Invoice = System.PrivateProfileString("C:\Users\Chad\Documents\BOLTemplate\" & _
"invoice-number.txt", "InvoiceNumber", "Invoice")
If Invoice = "" Then
Invoice = 1
Else
Invoice = Invoice + 1
End If
System.PrivateProfileString("C:\Users\Chad\Documents\BOLTemplate\" & _
"invoice-number.txt", "InvoiceNumber", "Invoice") = Invoice
'Insert the number in the document
ActiveDocument.Bookmarks(“Invoicenan”).Range.InsertBefore Format(Invoice, "")
ActiveDocument.SaveAs2 FileName:= _
"C:\Users\Chad\Documents\BOLTemplate\inv" & Format(Invoice, "") & ".docx" _
, FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=14
End Sub
我认为错误在于此行,因为它会生成数字,但不会插入它。
ActiveDocument.Bookmarks(“Invoicenan”).Range.InsertBefore Format(Invoice, "")
关于问题可能是什么想法?
答案 0 :(得分:0)
您的代码对我来说是正确的,所以这更像是一种调试方法而不是一种答案。为了解决这个问题,我会尝试将事情分解成微小的步骤以隔离故障。类似的东西:
Debug.Print "The active document is" " & ActiveDocument.Name
Dim wd as Word.Document
Set wd = ActiveDocument
Debug.Print "The document being created is" " & wd.Name
Dim bk as Word.Bookmark
Debug.Print "This document has these bookmarks"
For Each bk in wd.Bookmarks
Debug.Print bk.Name
If bk.Name = "Invoicenan" Then
Debug.Print "It's a match!"
Dim r as Word.Range
Set r = bk.Range
r.InsertBefore Format(Invoice, "")
End If
Next bk
如果找不到匹配项,那么请深入研究。比较" Invoicenan"以及应该匹配的书签。如果它们匹配,则通过char比较来执行char,等等。
希望这有帮助