简体   繁体   中英

Automatically execute Macro in word VBA

I have a macro which is executed while opening the word document. The problem is empty word object (Without file/doc) is opened macro works fine while opening a file/doc. If the fresh word document opened a file/doc then the macro doesn't work and shows error message.

My macro: Module1 -> normal.dot

Dim varData As Variant
Dim font_type() As String
Dim text As String
Dim font_name As Variant

varData = Array("?", "[[", "\tag", "$", "()", "|", "\label", "\ce", "insert_eq")

For Each font_name In varData
    Selection.HomeKey Unit:=wdStory
    Call ClearFindSettings
    Selection.Find.text = font_name
    If Selection.Find.Execute = True Then
          Selection.HomeKey Unit:=wdStory
          'Selection.TypeParagraph
          Selection.MoveUp
          alert_msg = "The '" & font_name & "' Text Present in doc"
          alert_msg_grp = alert_msg_grp & vbNewLine & alert_msg
    End If
 Next
 Call Error_alert(alert_msg_grp)
 End Sub

ThisDocument.

Private Sub Document_Open()
Call AutoExec
End Sub

Private Sub Document_New()
Call AutoExec
End Sub

Error Msg:

    Runtime Error '91'
    Selection.HomeKey Unit:=wdStory

Could someone help out on this one.

Please wrap around whether document is available, since application open no document is not opened that is why you got this error:

If (Application.Documents.Count > 0) Then
Dim varData As Variant
Dim font_type() As String
Dim text As String
Dim font_name As Variant

varData = Array("?", "[[", "\tag", "$", "()", "|", "\label", "\ce", "insert_eq")

For Each font_name In varData
    Selection.HomeKey Unit:=wdStory
    Call ClearFindSettings
    Selection.Find.text = font_name
    If Selection.Find.Execute = True Then
      Selection.HomeKey Unit:=wdStory
      'Selection.TypeParagraph
      Selection.MoveUp
      alert_msg = "The '" & font_name & "' Text Present in doc"
      alert_msg_grp = alert_msg_grp & vbNewLine & alert_msg
    End If
 Next
 Call Error_alert(alert_msg_grp)
END IF
 End Sub

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