如果
r = 1
, 和c = 1
下面的预期代码无效(它试图返回 Column 左侧两列的单元格A
)
Cells(r, c).Offset(0, -2)
如何检查预期的单元格在vba中是否有效?
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
这是给你的例子。
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