我有以下代码:
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模板中的所有字段。我的问题是,它是否可以更改为仅更新包含公式的字段?例如,当接收信息的字段包含{= SUM(Sect1A3)时,获取书签Sect1的值。
答案 0 :(得分:1)
这就是你能做到的。
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