2016-08-02 151 views
1

我知道這是完全錯誤的,但此刻,我真的不知道該怎麼做。VBA(Microsoft Excel)將字符串替換爲字符串

在Microsoft Excel中,我想通過固定字符串「NewValue」替換「OldValues」字符串上的所有值。這怎麼可能?

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 

回答

4

您的代碼應與小的改動來工作: 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 
+0

不錯的一個。不知道LBound&Ubound的函數是否正確(據我瞭解,它們的存在是爲了在數組上創建循環),所以我不知道如何使它工作。 –

+1

當與一個數組一起使用時,它們指向上下的索引邊界,所以對於Array(「old1」,「old2」,「old3」)的數組,'LBound'將爲0,UBound將爲2 – Jordan

+0

@MiguelRasquinho也可以使用變量類型的變量和For Each Loop循環遍歷數組。 'Dim x as Variant:For Each x in OldValues' – 2016-08-02 09:00:28