答案 0 :(得分:6)
Range
对象来测试它是否有效(多功能性首选)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
答案 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