首页 > 解决方案 > 使用 VB 窗体执行 Word 文档 VBA 宏

问题描述

我正在创建一个 VB 表单来帮助选择一个 word 文件,然后我可以使用另一个按钮操作来识别该文档中的 Content Controls 标记。问题是如何使用 Vb Form 运行任何 vba word 宏?下面是代码 -

Imports System.IO

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim fd As OpenFileDialog = New OpenFileDialog()
    Dim strFileName As String

    fd.Title = "Open File Dialog"
    fd.InitialDirectory = "C:\Users\%username%\Documents"
    fd.Filter = "Word Documents|*.doc;*.docx"
    fd.FilterIndex = 2
    fd.RestoreDirectory = True
    If fd.ShowDialog() = DialogResult.OK Then
        strFileName = fd.FileName
        PathLabel.Text = fd.FileName
        MsgBox("You have selected file -" & fd.FileName)

    End If
End Sub


Private Sub OpenFileDialog1_FileOk_1(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

End Sub

字宏 -

Sub GetCCs()
    Dim d As Document
    Set d = ActiveDocument
    Dim cc As ContentControl
    Dim sr As Range
    Dim srs As StoryRanges
    For Each sr In d.StoryRanges
        For Each cc In sr.ContentControls
            Debug.Print cc.Title
        Next
    Next
End Sub

抱歉,如果我在这里做错了什么,因为我对此很陌生!

谢谢!

标签: vb.netms-word

解决方案


您可以使用项目和模块来引用您的宏。IE...

Call prjMyProject.modMyModule.GetCCs

如果您的表单在同一个项目中,您可能会得到:

Call GetCCs
  • 注意 - 您的宏必须位于已加载的项目中(即附加模板、活动加载项)

推荐阅读