【问题标题】:Auto execute VBA Word macro on open打开时自动执行 VBA Word 宏
【发布时间】:2022-01-06 00:37:24
【问题描述】:

我在另一个网站上找到了这段代码,它完全按照我的意愿执行,除了我宁愿让 word 在模板打开时执行宏。我尝试过 Private Sub AutoOpen() 和 Private Sub document_open() 但似乎都不起作用。

我也不确定是否应该将其作为 .dotm 或 .docm。任何帮助表示赞赏,谢谢。

Sub CreateInvoiceNumber()

Invoice = System.PrivateProfileString("C:\Users\user\Documents\a\" & _ 
    "invoice-number.txt", "InvoiceNumber", "Invoice")

If Invoice = "" Then
    Invoice = 1
Else
    Invoice = Invoice + 1
End If

System.PrivateProfileString("C:\Users\user\Documents\a\" & _
    "invoice-number.txt", "InvoiceNumber", "Invoice") = Invoice

' Insert the number in the document
ActiveDocument.Range.InsertBefore Format(Invoice, "#")

ActiveDocument.SaveAs2 FileName:= _
 "C:\Users\user\Documents\a\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

【问题讨论】:

  • 您是指从模板创建的文档?你试过Document_Newevent 吗? Documentation
  • @RaymondWu 对不起,你的意思是不是Sub CreateInvoiceNumber()
  • 在问题的原始版本中看不到子名称,因此我对其进行了编辑。所以你想在从模板创建文档时运行CreateInvoiceNumber? @OliverSchilling
  • @RaymondWu 干杯,所以我已将其添加到文档中,但是当我在文件资源管理器中打开模板时,它不会在文档中添加数字或将其保存到文件位置。 (我正确设置了第二个用户)。
  • 你能用你现在拥有的任何东西来更新你的问题吗? Document_NewThisDocument 对象中的子对象吗?

标签: vba ms-word


【解决方案1】:

您拥有的是文档不是模板。当您误用术语模板时会令人困惑,因为它指的是创建新文档的 dotx/dotm 文件。每个文档都附加到创建它的模板。如果未使用特定模板,则它将附加到 Normal 模板。

要(错误)使用文档作为模板,您需要将 CreateInvoiceNumber 重命名为 AutoOpen,或者将例程中的代码作为 Document_Open 放入 ThisDocument 模块中

理想情况下,您应该正确使用 Word 并创建可以通过 File | 访问的发票模板。新的,在这种情况下,ThisDocument 例程将被命名为Document_New

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
相关资源
最近更新 更多