gpt4 book ai didi

vba - 从 Excel VBA 在 word doc 中执行查找和替换

转载 作者:行者123 更新时间:2023-12-04 20:10:32 28 4
gpt4 key购买 nike

我正在尝试根据 Excel 中的数据打开特定的 Word 模板(该部分正在工作)。然后,一旦打开模板,我就会尝试根据 Excel 文档中的标签进行查找并替换为同一列中的相应数据。当我运行宏时,它会打开模板并且只是旋转和旋转而不给我输出。这是代码:

` Sub New_Purification_SOP()
'
' New_Purification_SOP Macro
''Open an existing Word Document from Excel
Dim objWord As Object
Dim myValue As Variant
Dim PurCol As Variant
'open input box requesting line of the material to be made
myValue = InputBox("Select Row to create SOP")

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
'Change the directory path and file name to the location
'of the document you want to open from Excel
If ActiveSheet.Cells(myValue, 10) = "Supe" And _
ActiveSheet.Cells(myValue, 12) = "IgG1" Then
objWord.Documents.Open "S:\generic filename"
With objWord
For PurCol = 3 To 13 'move through columns left to right
TagName = .Cells(10, PurCol).Value 'get tag name from row
TagValue = .Cells(myValue, PurCol).Value 'get tag name from row
With objWord.Content.Find
.Text = TagName
.Replacement.Text = TagValue
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Forward = True, Wrap = _
wdFindContinue
End With
Next PurCol
End With`
...

我对 VBA 很陌生,所以请尽可能多地批评。

最佳答案

您可能希望在打开/创建 word 对象时包含错误处理。我发现如果我已经有一个 word up 的实例,它实际上可能会使应用程序崩溃。这可能会导致您的程序出现问题。

source: https://stackoverflow.com/questions/17177412/close-release-word-object-in-vba
On Error Resume Next
Set objWord = GetObject(, "Word.Application")

'We've tried to get Word but if it's nothing then it isn't open
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If

'It's good practice to reset error warnings
On Error GoTo 0

之后,查找/替换故障排除可能是一项痛苦的任务。请参阅这篇文章了解原因: https://gregmaxey.com/word_tip_pages/words_fickle_vba_find_property.html .您可能想要做的是使用宏记录器检查查找/替换代码,然后将其提升到您的循环中。它可以节省大量的调试时间。

关于vba - 从 Excel VBA 在 word doc 中执行查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50644736/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com