2013-03-08 47 views

回答

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 
+0

(1)檢查行和列; (2)更具體到'OP',並且只驗證列 – whytheq 2013-03-09 11:01:16

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 
+0

這是一個很長的路要走這個代碼明智 – brettdj 2013-03-08 07:46:23

+0

@ brettdj同意。 – 2013-03-08 08:27:58