读取工作表范围到VBA数组,使脚本超出范围错误

时间:2014-04-02 14:03:32

标签: arrays excel-vba vba excel

我通过将范围设置为我的数组

来改变宏

这很好用

Sub FindReplaceByArrays()

Dim FindValues As Variant
Dim ReplaceValues As Variant
Dim i As Long

FindValues = Array("Find1", "Find2", "Find3")
ReplaceValues = Array("Replace1", "Replace2", "Replace3")

Sheets("UnPivot").Select
For i = LBound(FindValues) To UBound(FindValues)
     Columns("P:P").Replace FindValues(i), ReplaceValues(i), xlWhole, xlByColumns, False
Next i

End Sub

厌倦了更改为以下Sub但得到错误"脚本超出范围`和

Columns("P:P").Replace FindValues(i), ReplaceValues(i), xlWhole, xlByColumns, False

高亮

由于

Sub FindReplaceByArrays2()

Dim FindValues() As Variant
Dim ReplaceValues() As Variant
Dim i As Long

Sheets("UnPivot").Select
FindValues = Range("S2:S30")
ReplaceValues = Range("T2:T30")

For i = LBound(FindValues) To UBound(FindValues)
     Columns("P:P").Replace FindValues(i), ReplaceValues(i), xlWhole, xlByColumns, False
Next i

End Sub

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub FindReplaceByArrays2()

    Dim FindValues As Variant
    Dim ReplaceValues As Variant
    Dim i As Long

    With Sheets("UnPivot")
        FindValues = .Range("S2:S30").Value
        ReplaceValues = .Range("T2:T30").Value

        For i = LBound(FindValues) To UBound(FindValues)
             .Columns("P:P").Replace FindValues(i, 1), ReplaceValues(i, 1), xlWhole, xlByColumns, False
        Next i
    End With
End Sub

请注意,我正在使用

  1. Dim FindValues As Variant代替Dim FindValues() As Variant
  2. FindValues = .Range("S2:S30").Value - .Value属性(您可以在此处阅读有关您应该使用它的原因:Why am I having issues assigning a Range to an Array of Variants
  3. FindValues = .Range("S2:S30").Value实际上也创建了2D数组,这就是我使用FindValues(i, 1)的原因。 ReplaceValues(i, 1)
  4. 也是如此

    还有:How to avoid using Select/Active statements:)