方法'价值'对象'范围'失败

时间:2016-04-05 19:32:08

标签: excel vba excel-vba

以下VBA代码片段在大约80k行的excel列上尝试使用简单的If语句。发生以下错误。

运行时错误' -2147417848(80010108)': 方法'价值'对象'范围'失败

这里出了什么问题?

Dim r As Long
Dim lastrow As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
For r = 2 To lastrow
    If InStr(Range("I" & r).Text, "WH") Then
        Range("Z" & r).Value = "O"
    ElseIf InStr(Range("I" & r).Text, "MOD") Then
        Range("Z" & r).Value = "M"
    ElseIf InStr(Range("I" & r).Text, "VER") Then
        Range("Z" & r).Value = "V"
    ElseIf InStr(Range("I" & r).Text, "WT") Then
        Range("Z" & r).Value = "WT"
    ElseIf InStr(Range("E" & r).Text, "OIL") Then
        Range("Z" & r).Value = "OIL"
    Else: Range("Z" & r).Value = "N"
    End If
Next r

1 个答案:

答案 0 :(得分:3)

VBA环境不能免于不稳定。如果您遇到多次崩溃,请保存您的工作并重新启动计算机(冷启动)。

话虽如此,这些例程中的每一个都在不到半秒的时间内运行,而不是原始的通过80K单元的27秒。

Sub oilWT2()
    Dim r As Long, vVALs As Variant

    Debug.Print Timer
    With Worksheets("Sheet5")
        vVALs = .Range(.Cells(2, "I"), .Cells(rows.Count, "A").End(xlUp).Offset(0, 8)).Value2
        For r = LBound(vVALs, 1) To UBound(vVALs, 1)
            Select Case UCase(vVALs(r, 1))
                Case "WH"
                    vVALs(r, 1) = "O"
                Case "MOD", "VER"
                    vVALs(r, 1) = Right(vVALs(r, 1), 1)
                Case "WT", "OIL"
                    'do nothing - value already correct
                Case Else
                    vVALs(r, 1) = "N"
            End Select
        Next r
        .Cells(2, "Z").Resize(UBound(vVALs, 1), 1) = vVALs
    End With
    Debug.Print Timer
End Sub

Sub oilWT3()
    Dim r As Long, vVALs As Variant

    Debug.Print Timer
    With Worksheets("Sheet5")
        vVALs = .Range(.Cells(2, "I"), .Cells(rows.Count, "A").End(xlUp).Offset(0, 8)).Value2
        For r = LBound(vVALs, 1) To UBound(vVALs, 1)
            Select Case True
                Case CBool(InStr(1, vVALs(r, 1), "WH", vbTextCompare))
                    vVALs(r, 1) = "O"
                Case CBool(InStr(1, vVALs(r, 1), "MOD", vbTextCompare)) Or _
                     CBool(InStr(1, vVALs(r, 1), "VER", vbTextCompare))
                    vVALs(r, 1) = Right(vVALs(r, 1), 1)
                Case CBool(InStr(1, vVALs(r, 1), "WT", vbTextCompare))
                    vVALs(r, 1) = "WT"
                Case CBool(InStr(1, vVALs(r, 1), "OIL", vbTextCompare))
                    vVALs(r, 1) = "OIL"
                Case Else
                    vVALs(r, 1) = "N"
            End Select
        Next r
        .Cells(2, "Z").Resize(UBound(vVALs, 1), 1) = vVALs
    End With
    Debug.Print Timer
End Sub

前者只是看整个细胞内容;后者使用InStr function来搜索原始字符串中的字符串。通过重用变量数组来存储新值,它使条件语句比逐个单元读取更有效。类似地将值 en masse 返回到Z列。