Excel VBA 查找和替换

标签 excel vba replace find

我有这段代码,它工作得很好。现在我需要改变它,但我不知道该怎么做。

代码在整个wordksheet中进行搜索。我只需要在 1 列中搜索

代码搜索整个单元格。我需要搜索单元格的左侧、中间或右侧。

Sub ChgInfo() 

Dim WS As Worksheet 
Dim Search As String 
Dim Replacement As String 
Dim Prompt As String 
Dim Title As String 
Dim MatchCase As Boolean 

Prompt = "What is the original value you want to replace?" 
Title = "Search Value Input" 
Search = InputBox(Prompt, Title) 

Prompt = "What is the replacement value?" 
Title = "Search Value Input" 
Replacement = InputBox(Prompt, Title) 

For Each WS In Worksheets 
WS.Cells.Replace What:=Search, Replacement:=Replacement, _ 
LookAt:=xlPart, MatchCase:=False 
Next 

End Sub

最佳答案

这是您要找的吗?

下面的代码将在每个工作表的 A 列中查找值。

Sub ChgInfo()

    Dim WS As Worksheet
    Dim Search As String
    Dim Replacement As String
    Dim Prompt As String
    Dim Title As String
    Dim MatchCase As Boolean

    Prompt = "What is the original value you want to replace?"
    Title = "Search Value Input"
    Search = InputBox(Prompt, Title)

    Prompt = "What is the replacement value?"
    Title = "Search Value Input"
    Replacement = InputBox(Prompt, Title)

    For Each WS In Worksheets
        WS.Columns(1).Replace What:=Search, Replacement:=Replacement, LookAt:=xlPart, MatchCase:=False
    Next

End Sub

更新答案

Sub ChgInfo()

    Dim WS As Worksheet
    Dim Search As String
    Dim Replacement As String
    Dim Prompt As String
    Dim Title As String
    Dim MatchCase As Boolean
    Dim cell As Range
    Dim rngFind As Range
    Dim firstCell As String

    Prompt = "What is the original value you want to replace?"
    Title = "Search Value Input"
    Search = Trim(InputBox(Prompt, Title))

    Prompt = "What is the replacement value?"
    Title = "Search Value Input"
    Replacement = Trim(InputBox(Prompt, Title))

    For Each WS In Worksheets
        Set rngFind = WS.Columns(1).Find(What:=Search, LookIn:=xlValues, lookat:=xlPart)

        If Not rngFind Is Nothing Then firstCell = rngFind.Address

        Do While Not rngFind Is Nothing
            rngFind = Replacement & Mid(rngFind, 5, Len(rngFind))
            Set rngFind = WS.Columns(1).FindNext(After:=rngFind)
            If firstCell = rngFind.Address Then Exit Do
        Loop
    Next

End Sub

关于Excel VBA 查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17684155/

相关文章:

ms-access - 如何让我的 webbrowser-control 的内容在打印时显示在我的 MS Access 报告中?

Sqlite,用斜杠替换反斜杠

c# - 如何一次性执行多个字符串替换?

regex - Perl:在多个文本文件中查找和替换特定字符串

excel - 当我循环通过 ActiveWorkbook.Names 并尝试使用 VBA 删除命名范围时,为什么会出现 1004 错误?

VBA 宏在 32000 行后崩溃

vba - 如何将大型(最大 10Mb)文本文件嵌入到 Excel 文件中

mysql - 我应该多久索引一次?

java - 使用 apache poi 写入 xlsm (Excel 2007)

arrays - ReDim 保留二维变量数组