VBA(Microsoft Excel)用StringreplaceArray

我知道这是完全错误的,但此刻,我真的不知道该怎么做。

在Microsoft Excel中,我想通过固定string“NewValue”来replace“OldValues”string上的所有值。 这怎么可能?

LBound和Ubound是错误的使用,对吧?

Sub Replace() Dim sht As Worksheet Dim OldValues As Variant Dim NewValue As String Dim x As Long OldValue = Array("old1","old2","old3") NewValue = "allnew!" For x = LBound(OldValue) To UBound(NewValue) For Each sht In ActiveWorkbook.Worksheets sht.Cells.Replace What:=OldValue(x), Replacement:=NewValue(x), _ LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _ SearchFormat:=False, ReplaceFormat:=False Next sht Next x End Sub 

你的代码应该NewValue微小的改变: NewValue不是一个数组,所以UBound(NewValue)会给你一个错误。 您必须在循环中使用UBound(OldValues) ,并在Replace删除NewValue后面的(x)

 Sub Replace() Dim sht As Worksheet Dim OldValues As Variant Dim NewValue As String Dim x As Long OldValues = Array("old1","old2","old3") NewValue = "allnew!" For x = LBound(OldValues) To UBound(OldValues) For Each sht In ActiveWorkbook.Worksheets sht.Cells.Replace What:=OldValues(x), Replacement:=NewValue, _ LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _ SearchFormat:=False, ReplaceFormat:=False Next sht Next x End Sub