Search and Replace a number of characters in Excel

2019-05-11 23:45发布

问题:

I need to search and to replace a specific part of a string in an Excel sheet.

Here is my code and I don't know how I can exactly search this part in each Cell.value.

my_new_string = "abc"
For each objSheet1 in objworkbook2.sheets
    If objSheet1.Name = "Name1" Then
        LastRow = objsheet1.UsedRange.Rows.Count + objsheet1.UsedRange.Row - 1
        For i = 1 To LastRow Step 1
            For j = 1 To 15 Step 1
                If objExcel1.Cells(i, j).value = "xyz" Then 'Here I have to check if the Cell value contains xyz and to replace it by **my_new_string**
                End if
            Next
        Next
    End If
Next

Any help please ?

回答1:

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


回答2:

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