在VBA中使用UserForm更新Word中的DocVariables

在VBA中使用UserForm更新Word中的DocVariables,vba,ms-word,docvariable,Vba,Ms Word,Docvariable,我已经在word模板中创建了DocVariables,并使用UserForm允许用户输入来填充这些变量 以下是我一直使用的代码: Private Sub CommandButton1_Click() Dim ReportTitle, reportSub As String ReportTitle = Me.textBox1.Value reportSub = Me.textBox2.Value ActiveDocument.Variables("Report Title"

我已经在word模板中创建了DocVariables,并使用UserForm允许用户输入来填充这些变量

以下是我一直使用的代码:

Private Sub CommandButton1_Click()

Dim ReportTitle, reportSub As String

ReportTitle = Me.textBox1.Value
reportSub = Me.textBox2.Value

ActiveDocument.Variables("Report Title").Value = ReportTitle
ActiveDocument.Variables("Sub-Title").Value = reportSub

ActiveDocument.Fields.Update

Me.Repaint

End Sub
这会将文本框中的值插入变量,但不会更新字段,因此我必须手动转到每个字段并更新它

你能告诉我哪里出了问题,这样我就可以解决这个问题了

非常感谢您的帮助。

请尝试:

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
With ActiveDocument
  .Variables("Report Title").Value = Me.textBox1.Value
  .Variables("Sub-Title").Value = Me.TextBox2.Value
  .Fields.Update
  .PrintPreview
  .ClosePrintPreview
End With
Me.Repaint
Application.ScreenUpdating = True
End Sub

你看起来不太努力。一个简单的Bing/Google搜索会给你答案,你也可以在这里找到: