简体   繁体   中英

Auto execute VBA Word macro on open

I have this code I found off another website which performs exactly how I wish except I'd rather have word execute the macro on the open of the template. I have tried Private Sub AutoOpen() and Private Sub document_open() but neither seemed to work.

I am also unsure if I should have it as a.dotm or.docm. Any help is appreciated, Thank you.

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

What you have is a document not a template. It is confusing when you misuse the term template as it refers to a dotx/dotm file from which new documents are created. Every document is attached to the template it was created from. If a specific template was not used then it will be attached to the Normal template.

To (mis)use a document as a template you would need to rename CreateInvoiceNumber as AutoOpen , or put the code from your routine into the ThisDocument module as Document_Open

在此处输入图像描述

Ideally you would use Word correctly and create an invoice template that can be accessed via File | New, in which case the ThisDocument routine would be named Document_New

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM