且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python查找并替换Excel(.xlsx)中的字符串

更新时间:2023-02-21 15:38:23

我将复制你的内容将文本文件导入Excel文件中的新工作表,并将该表格命名为Lookup。然后使用文本列将数据从第一行开始获取此新表格前两列中的数据。

I would copy the contents of your text file into a new worksheet in the excel file and name that sheet "Lookup." Then use text to columns to get the data in the first two columns of this new sheet starting in the first row.

将以下代码粘贴到Excel中的模块中,并运行它:

Paste the following code into a module in Excel and run it:

Sub Replacer()
    Dim w1 As Worksheet
    Dim w2 As Worksheet

    'The sheet with the words from the text file:
    Set w1 = ThisWorkbook.Sheets("Lookup")
    'The sheet with all of the data:
    Set w2 = ThisWorkbook.Sheets("Data")

    For i = 1 To w1.Range("A1").CurrentRegion.Rows.Count
        w2.Cells.Replace What:=w1.Cells(i, 1), Replacement:=w1.Cells(i, 2), LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Next i

End Sub