0

我对 VBA 一点也不熟悉。我在网上找到了一个代码,可以让我同时替换几个单词。一年前我找到了它,但我现在找不到它,所以不能把它归功于写它的人(我的意思是,它不是我写的)。

它工作得很好,但是我不想在 VBscript 中输入 StrFind 和 StrRepl 中的所有单词,而是想从包含单词列表和相应替换单词的文本文件中加载单词。

这是代码:

Sub MultiReplace()
Dim StrFind As String, StrRepl As String

Dim i As Long
StrFind = "word1, word2, word3"
StrRepl = "hello1, hello2, hello3"
Set RngTxt = Selection.Range
For i = 0 To UBound(Split(StrFind, ","))

Selection.HomeKey wdStory
Selection.Find.ClearFormatting
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = Split(StrFind, ",")(i)
.Replacement.Text = Split(StrRepl, ",")(i)
.Format = False
.MatchWholeWord = True
.MatchAllWordForms = False
.MatchWildcards = False
.Execute Replace:=wdReplaceAll
End With
Next i
'
End Sub

我想调整行 StrFind = "word1, word2, word3" StrRepl = "hello1, hello2, hello3" 所以它从文本文件中获取数据,这是因为如果我有很多单词/字母,我会得到一个错误。

这是文本文件的外观:list.txt:

word1 == hello1
word2 == hello2

它不需要是一个 txt 文件,一个 excel 也可以工作(但我想保持在 word 中运行脚本的超快时间)。

感谢帮助

4

1 回答 1

0

您可以将 list.txt 导入您的 excel 文件,然后从您的 excel 文件单元格中读取内容。

为确定的操作检索 VBA 代码的一个非常有用的工具是宏记录器,在功能区中,Developer -> RecordMacro,执行您的操作并停止录制,然后您可以检查为您录制的操作生成的代码。它不是最干净的代码,但您可以在那里找到您想要的特定操作的代码行。一旦你用你尝试的代码遇到了一个具体的问题,你就可以就更具体的事情寻求帮助,而不是期望有人会为你编写代码。

从我的一个随机 txt 文件中找到这个 .txt 内容导入代码,只需记录您在使用用户操作导入 .txt 时的步骤:

Sub Importtxt()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\Usuario\Desktop\YourFileName.txt", Destination:=Range("$A$1") _
        )
        .CommandType = 0
        .Name = "YourFileName"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 1252
        .TextFileStartRow = 1
        .TextFileParseType = xlFixedWidth
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(2, 1, 1, 1)
        .TextFileFixedColumnWidths = Array(117, 2, 3)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

可以在此处找到要遵循的用户操作。从这里开始,您需要在导入后从您的 excel 文件中读取StrFind和读取,并在您的工作宏中相应地应用这些值。StrRepl

希望有帮助

于 2020-06-29T08:04:12.827 回答