Vba 仅更新Microsoft Word中包含公式的字段
我有以下代码:Vba 仅更新Microsoft Word中包含公式的字段,vba,ms-word,Vba,Ms Word,我有以下代码: Private WithEvents App As Word.Application Private Sub Document_Open() Set App = Word.Application ActiveDocument.Fields.Update End Sub Private Sub App_WindowSelectionChange(ByVal Sel As Selection) ActiveDocument.Fields.Update End Sub
Private WithEvents App As Word.Application
Private Sub Document_Open()
Set App = Word.Application
ActiveDocument.Fields.Update
End Sub
Private Sub App_WindowSelectionChange(ByVal Sel As Selection)
ActiveDocument.Fields.Update
End Sub
此代码自动更新Word模板中的所有字段。我的问题是,是否可以将其更改为仅更新包含公式的字段?例如,当接收信息的字段包含{=SUMSect1A3时,获取bookmark Sect1的值。这就是您可以实现的方法
Private WithEvents App As Word.Application
Private Sub Document_Open()
Set App = Word.Application
UpdateSumFields
End Sub
Private Sub App_WindowSelectionChange(ByVal Sel As Selection)
UpdateSumFields
End Sub
Private Sub UpdateSumFields()
Dim field As field
For Each field In ActiveDocument.Fields
If CStr(field.Code) Like "*=SUM(Sect1A3)*" Then
field.Update
End If
Next field
End Sub
在like语句中放入任何内容。我相信有更好的方法使其更可重用。可能使用一个数组,其中包含多个字段,您希望在一个目标中更新这些字段
下面是一个例子:
Private Sub UpdateFieldExtended()
Dim field As field
Dim fieldCodePattern(1 To 5) As String
fieldCodePattern(1) = "=SUM"
fieldCodePattern(2) = "TOC"
fieldCodePattern(3) = "REF"
fieldCodePattern(4) = "STYLEREF"
fieldCodePattern(5) = "DATE"
For Each field In ActiveDocument.Fields
If IsInArray(CStr(field.Code), fieldCodePattern) Then
field.Update
End If
Next field
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
For i = 1 To UBound(arr)
If Trim(stringToBeFound) Like "*" + arr(i) + "*" Then
IsInArray = True
Exit For
End If
Next i
End Function