我有一个.xlsm工作簿,其中VBA(见下文(与Word文档交互以替换字段代码。看起来很直接,而且效果很好。。。
然后我把代码复制粘贴到一个新的.xlsm中,检查单元格、工作表名称和内容,一切都一样!VBA将运行,我没有收到任何错误。但是,使用新的.xlsm,文档中的字段代码将不再被替换!我在网上没有找到任何有用的东西。。。想法?
顺便说一句,我不确定这是否相关,但我的";num锁";在测试此脚本/函数期间,有时会打开/关闭。
Sub Exl_to_Wrd_FieldReplace()
'
' Exl_to_Wrd_FieldReplaceMacro
'
' Setup info for document and captures default DIR for Document
Dim wordapp As Object
Dim folderPath As String
Dim wordDoc As String
folderPath = Application.ThisWorkbook.Path
wordDoc = folderPath & "TestDoc.docx"
'
' Assign Excel cell values for Field Code Text Replacement
Dim CaseNum As String: CaseNum = Range("C36").Value
Dim P1LastName As String: P1LastName = Range("C41").Value
Dim P2FInl As String: P2FInl = Range("C53").Value
Dim P2LastName As String: P2LastName = Range("C54").Value
Dim P2ID As String: P2ID = Range("C55").Value
'
' Open Word application and document
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open (wordDoc) 'Uses path from above & Doc name
wordapp.Visible = True
wordapp.Activate
'
' Converts Field Vaule text to Field Codes (i.e. ALT + F9)
SendKeys "%{F9}"
'
' Starts the Find Command to replace field code with hard coded text
With wordapp.ActiveDocument.Content.Find
'
' Finds 1st field code
.Text = "^d DOCPROPERTY IBA|CaseNumber * MERGEFORMAT"
.ClearFormatting
.Replacement.Text = CaseNum
.Execute Replace:=wdReplaceAll
' Finds 2nd field code
.Text = "^d DOCPROPERTY IBA|P1LastName * MERGEFORMAT"
.ClearFormatting
.Replacement.Text = P1LastName
.Execute Replace:=wdReplaceAll
' Finds 3rd field code
.Text = "^d DOCPROPERTY IBA|P2FirstInitial * MERGEFORMAT"
.ClearFormatting
.Replacement.Text = P2FInl
.Execute Replace:=wdReplaceAll
' Finds 4th field code
.Text = "^d DOCPROPERTY IBA|P2LastName * MERGEFORMAT"
.ClearFormatting
.Replacement.Text = P2LastName
.Execute Replace:=wdReplaceAll
' Finds 5th field code
.Text = "^d DOCPROPERTY IBA|P2Number * MERGEFORMAT"
.ClearFormatting
.Replacement.Text = P2ID
.Execute Replace:=wdReplaceAll
'
End With
'
' Converts Field Codes back to Field Vaule text (i.e. ALT + F9)
SendKeys "%{F9}"
'
' It is ok to leave doc open, user needs to do final check/edit before save
'
End Sub
我检查了excel表、链接、VBA和Xml,都是一样的。
使用SendKeys通常非常不可靠。要切换word中字段的显示,可以使用ShowFieldCodes
,它是View
-对象的属性,也是Window
的属性。
With wordApp.ActiveDocument.ActiveWindow.View
.ShowFieldCodes = True ' Shows the Code
.ShowFieldCodes = False ' Shows the Content
.ShowFieldCodes = Not .ShowFieldCodes ' Toggles the setting (this is what Alt+F9 does)
End With