值不存在時出錯

值不存在時出錯

我在一個子程式中多次使用下面的程式碼來取得不同的值,而不僅僅是「CPNEC」。當電子表格上存在包含該值的範圍但超出該範圍時該值不存在時,它可以正常工作。這是我每個月都想使用的例程,有時我的資料中沒有某個值,所以我需要它能夠移動到下一個值而不會失敗。任何人都可以幫助我嗎?

Sub SelectCPNEC()
    ' Figure out where the "CPNEC" data starts.
    For nRow = 1 To 65536
    If Range("A" & nRow).Value = "CPNEC" Then
    nStart = nRow
    Exit For
    End If
    Next nRow

    ' Figure out where the "CPNEC" data ends.
    For nRow = nStart To 65536
    If Range("a" & nRow).Value <> "CPNEC" Then
    nEnd = nRow
    Exit For
    End If
    Next nRow
    nEnd = nEnd - 1

    'Select the range required

    Range("A" & nStart & ":G" & nEnd).Select

    'Now copy and paste into the right worksheet

    Selection.Copy
    Application.Goto ActiveWorkbook.Sheets("CPNEC").Cells(1, 1)
    ActiveSheet.Paste

End Sub

答案1

當不存在匹配值時,nStart保留預設值0。這會導致該行出現錯誤。

If Range("a" & nRow).Value <> "CPNEC" Then

因為A0不是有效的範圍參考。為了解決這個問題(並避免一些不必要的循環),請nStart = 0在第一個循環之後添加條件檢查。如果為零,則退出子進程;否則,繼續。這應該可以避免在找不到匹配項時停止程式碼的錯誤。

Sub SelectCPNEC()
    ' Figure out where the "CPNEC" data starts.
    For nRow = 1 To 65536
    If Range("A" & nRow).Value = "CPNEC" Then
    nStart = nRow
    Exit For
    End If
    Next nRow

    If nStart > 0 Then
        ' Figure out where the "CPNEC" data ends.
        For nRow = nStart To 65536
        If Range("A" & nRow).Value <> "CPNEC" Then
        nEnd = nRow
        Exit For
        End If
        Next nRow
        nEnd = nEnd - 1

        'Select the range required

        Range("A" & nStart & ":G" & nEnd).Select

        'Now copy and paste into the right worksheet

        Selection.Copy
        Application.Goto ActiveWorkbook.Sheets("CPNEC").Cells(1, 1)
        ActiveSheet.Paste
    End If
End Sub

答案2

Excelll 對此進行了解釋。但是,由於您可以很好地處理 for 循環,因此您也可以搜尋每個儲存格上的字串,如果巨集找到它,則將整行複製到正確的工作表中。如果該值不存在,您不會收到錯誤訊息。

For Each cell In Range("A1: A65536")
    If cell.Value = "CPNEC" Then
        cell.EntireRow.Copy Workbooks.Open("otherWorkbook.xls").Sheets("Sheet1").Range("A1").End(xlDown).Offset(1, 0)
    End If
Next cell

在儲存格「A1」和儲存格「A2」中應該有一些訊息,例如列標題。.End(xlDown).Offset(1,0)會找到第一個空行來貼上訊息。

相關內容