4

如果

  • r = 1, 和
  • c = 1

下面的预期代码无效(它试图返回 Column 左侧两列的单元格A

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

如何检查预期的单元格在中是否有效?

4

2 回答 2

6
  1. 使用一个Range对象来测试它是否有效(通用性优先)
  2. 测试该列是否有效(假设您的硬编码OFFSET(0,2)

(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
于 2013-03-08T03:00:01.787 回答
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
于 2013-03-08T05:13:06.077 回答