简体   繁体   English

VBA(Microsoft Excel)用字符串替换数组

[英]VBA (Microsoft Excel) replace Array with String

I know this is completely wrong, but at the moment, I really don't know how to do it. 我知道这是完全错误的,但是目前,我真的不知道该怎么做。

In Microsoft Excel, I want to replace all the values on the "OldValues" string, by a fixed string "NewValue". 在Microsoft Excel中,我想用固定的字符串“ NewValue”替换“ OldValues”字符串上的所有值。 How is that possible? 那怎么可能?

LBound and Ubound are wrong to be used, right? 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

Your code should be working with minor changes: NewValue is not an array, so UBound(NewValue) will get you an error. 您的代码应该进行较小的更改: NewValue不是数组,因此UBound(NewValue)会给您一个错误。 You have to go up to UBound(OldValues) instead in your loop, and remove the (x) after NewValue in the Replace . 您必须在循环中转到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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM