使用VBscript在Excel中search和replace一些字符

我需要search并replaceExcel工作表中的string的特定部分。

这是我的代码,我不知道如何在每个Cell.value完全search这部分。

 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 

请帮忙吗?

谢谢你们,

这对我来说工作得很好。

 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 

我改变了find最后一行的方法,使其更可靠。

你也用2个不同的物体来描述同一张纸,所以我就修好了! ;)

最后,你只需要使用Replace方法就可以很好地完成这个工作,而不需要testing这个string是否与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