如何在VBA中检查单元格是否有效?

时间:2013-03-08 02:26:10

标签: excel vba excel-vba

如果

  • r = 1
  • c = 1

下面的目标代码无效(它尝试将列格A左侧的单元格返回两列)

Cells(r, c).Offset(0, -2)

如何在

中检查目标单元格是否有效

2 个答案:

答案 0 :(得分:6)

  1. 使用Range对象来测试它是否有效(多功能性首选)
  2. 测试该列是否有效(假设OFFSET的硬代码为(0,2)
  3. (1)代码

    Sub Test1()
    Dim r As Long
    Dim c As Long
    r = 1
    c = 1
    Dim rng1 As Range
    On Error Resume Next
    Set rng1 = Cells(r, c).Offset(0, -2)
    On Error GoTo 0
    If Not rng1 Is Nothing Then
    'proceed with your code - range exists
    Else
    MsgBox "Range Error", vbCritical
    End If
    End Sub
    

    (2)代码

    Sub Test2()
    Dim rng1 As Range
    Dim r As Long
    Dim c As Long
    c = 3
    r = 1
    If c - 2 <= 0 Then
    MsgBox "Error", vbCritical
    Else
    Set rng1 = Cells(r, c).Offset(0, -2)
    End If
    End Sub
    

答案 1 :(得分:1)

以下是您的示例。

Sub sample()

    Dim r As Integer
    Dim c As Integer
    r = 1
    c = 1


    Dim validRng As Boolean
    validRng = isValidRng(r, c, 0, -2)
    Debug.Print validRng

    validRng = isValidRng(r, c + 5, 0, 2)
    Debug.Print validRng

     validRng = isValidRng(r, c, -1, 0)
    Debug.Print validRng

     validRng = isValidRng(r, c + 2, 0, -1)
    Debug.Print validRng

End Sub

Function isValidRng(row As Integer, col As Integer, offsetrow As Integer, offsetcol As Integer) As Boolean
'Returns if its valid range
    If ((row + offsetrow) > 0) And ((col + offsetcol) > 0) Then
        isValidRng = True
    Else
        isValidRng = False
    End If
End Function