根据我的数组替换字符串中的字符串 - 获取对象错误

时间:2017-11-10 17:41:48

标签: arrays vba runtime-error

Sub clean()

Dim x As Long, lastrow As Long
Dim ws As Worksheet
Dim CleanAry
Set ws = ThisWorkbook.Sheets("Sheet1")
'copy Column B to C
'Range("B1:B1048576").Copy Destination:=ws.Range("C1:C1048576")

'array for clean up

CleanAry = Array("..", "__")

lastrow = ws.Range("C1048576").End(xlUp).Row

For Each cel In Range("C1:C" & lastrow)
    For i = LBound(CleanAry) To UBound(CleanAry)
            cel = cel.Replace(What:=CleanAry(i), _
                            Replacement:=".", _
                            Lookat:=xlPart, _
                            SearchOrder:=xlByRows, _
                            MatchCase:=False)
    Next i
Next cel
End Sub

我正在尝试创建一个字符串组合数组,这些字符串组合将解析特定列,并从单元格中的现有字符串中删除这些字符串组合。

但是,我的代码只在我的数组中有一个字符串时才起作用,而不是在我添加其他字符串时。我收到错误:

  

“cel = ...”部分的“需要对象”。

没有真正一致地在VBA中编码。帮我弄清楚出了什么问题。

1 个答案:

答案 0 :(得分:0)

如果您预计正在清理的范围内可能存在错误,您应该添加一些检查。使用数组整个过程会快得多。

Sub clean()

    Dim x As Long, lastrow As Long
    Dim ws As Worksheet
    Dim CleanAry, v, arr, r As Long
    Set ws = ThisWorkbook.Sheets("Sheet1")
    'copy Column B to C
    'Range("B1:B1048576").Copy Destination:=ws.Range("C1:C1048576")

    CleanAry = Array("..", "__")   'array for clean up

    lastrow = ws.Range("C1048576").End(xlUp).Row
    arr = Range("C1:C" & lastrow).Value
    For r = 1 to UBound(arr, 1)
        v = arr(r, 1)
        For i = LBound(CleanAry) To UBound(CleanAry)
                v = Replace(v, CleanAry(i), ".")
        Next i
        arr(r, 1) = v
    Next r
    Range("C1:C" & lastrow).Value = arr
End Sub