我需要在Excel工作表中搜索并替换字符串的特定部分。
这是我的代码,我不知道如何在每个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
请帮忙吗?
答案 0 :(得分:3)
谢谢大家,
这对我来说很好。
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
答案 1 :(得分:2)
我将查找最后一行的方法更改为更可靠的方法。
您还使用了2个不同的对象来描述同一张纸,所以我修复了它! ;)
最后,您只需要使用Replace
方法完美地完成工作,而无需测试字符串是否与Instr
一起使用(如果您还有其他任何事情可以使用它检测到old_string)
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