简体   繁体   English

查找用宏替换MS Word

[英]Find replace MS Word with Macro

I have written a macro that replaces a file path with the current files location in Word 2016. 我编写了一个宏,用Word 2016中的当前文件位置替换文件路径。

Dim i As Long, j As Long
Dim s As String
s = ActiveDocument.Path
Dim sa As String
sa = Replace(s + "\test1.xlxs", "\", "\\")

For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "C:*test1.xlsx"
        .Replacement.Text = sa
        .MatchWildcards = True
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
Next myStoryRange


End Sub

This shows the error "the replacement text contains a group number that is out of range" 这将显示错误“替换文本包含超出范围的组号”

The 'sa' variable has the correct string in it, i checked this at run time. “ sa”变量中包含正确的字符串,我在运行时检查了此字符串。 Also when i replace 当我更换时

.Replacement.Text = sa

with

.Replacement.Text = "bla"

It works. 有用。 At run time an example of 'sa' would be "C:\\\\Users\\\\Me\\\\Documents\\\\test1.xlsx" 在运行时,“ sa”的示例为“ C:\\\\ Users \\\\ Me \\\\ Documents \\\\ test1.xlsx”

Does anyone have any suggestions what might be the problem? 有人有什么建议可能是什么问题吗?

Wildcards and backslashes do not work well together when finding and replacing text - the backslash has its own particular use. 查找和替换文本时,通配符和反斜杠不能很好地配合使用-反斜杠有其特殊的用途。

To replace a backslash in this case, use its ASCII equivalent: "^92^92" instead of "\\\\" . 在这种情况下,要替换反斜杠,请使用等效的ASCII: "^92^92"而不是"\\\\"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM