Search and Replace a number of characters in Excel using VBscript

偶尔善良 提交于 2019-12-06 00:12:46
sourh

Thank you all,

this is working fine for me.

For Each objsheet1 In objworkbook2.Sheets
    With objsheet1
        If .Name = "BatchRun" Then
            On error resume next
            For i = 1 To 15 Step 1
                For j = 1 To 10 Step 1
                    If InStr(1, .Cells(i, j).Value, my_old_string) > 0 Then
                        .Cells(i, j).Value = Replace(.Cells(i, j).Value, my_old_string, my_new_string)
                    End If
                Next
            Next 
        End If
    End with
Next
R3uK

I changed your method for finding the last row to one that is much more reliable.

Also you used 2 different objects to describe the same sheet, so I fixed it! ;)

Finally, you just need to use Replace method that will do the job perfectly fine, without need to test if the string is present with Instr (use it if you anything else to do if the old_string is detected)

Const my_old_string = "xyz"
Const my_new_string = "abc"
Const xlPart = 2
Const xlFormulas = -4123
Const xlByRows = 1
Const xlPrevious = 2


For Each objsheet1 In objworkbook2.Sheets
    With objsheet1
    If .Name = "Name1" Then
        LastRow = .Cells.Find("*",.Range("A1"),xlPart,xlFormulas,xlByRows,xlPrevious,False).Row
        For i = 1 To LastRow Step 1
            For j = 1 To 15 Step 1
                .Cells(i, j).Value = Replace(.Cells(i, j).Value, my_old_string, my_new_string)
'                If InStr(1, .Cells(i, j).Value, my_old_string) Then
'                    .Cells(i, j).Value = Replace(.Cells(i, j).Value, my_old_string, my_new_string)
'                End If
            Next
        Next 
    End If
    End With
Next
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!