2011-03-03 86 views
11

我想測試給定的單元格是否在Excel VBA中的給定範圍內。做這個的最好方式是什麼?VBA測試如果單元格在一個範圍內

+9

有關建議答案的任何反饋?不檢查提出的答案並不酷,因爲答案花費他們的時間尋找您的解決方案。 – 2011-03-04 14:49:31

回答

5

Determine if a cell is within a range using VBA in Microsoft Excel

從鏈接網站(保持信貸最初的提交者):

VBA宏尖貢獻的Erlandsen Data Consulting 提供Microsoft Excel應用程序的開發,模板定製, 支持和培訓解決方案

Function InRange(Range1 As Range, Range2 As Range) As Boolean 
    ' returns True if Range1 is within Range2 
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing) 
End Function 


Sub TestInRange() 
    If InRange(ActiveCell, Range("A1:D100")) Then 
     ' code to handle that the active cell is within the right range 
     MsgBox "Active Cell In Range!" 
    Else 
     ' code to handle that the active cell is not within the right range 
     MsgBox "Active Cell NOT In Range!" 
    End If 
End Sub 
+0

@ mwolfe02前一段時間,我發佈了一個外部鏈接,並建議粘貼代碼而不是鏈接本身(以避免外部網站脫機或類似問題)。 所以,我建議你粘貼代碼_plus_的鏈接。 – 2011-03-03 17:01:02

+0

@Tiago:由於潛在的版權問題,我很猶豫。我添加了原始的署名,以便爲作者提供公平的到期日。希望這可以在剽竊和樂於助人之間劃清界限。 – mwolfe02 2011-03-03 17:21:40

+0

@ mwolfe02同意,好友。我只是遵循其他用戶的建議,因爲我是這裏的新手。 – 2011-03-03 18:59:31

26

從幫助:

Set isect = Application.Intersect(Range("rg1"), Range("rg2")) 
If isect Is Nothing Then 
    MsgBox "Ranges do not intersect" 
Else 
    isect.Select 
End If 
+0

這不受'Application.Intersect'中的錯誤的保護。看[這個答案](http://stackoverflow.com/a/27838714/2707864) – 2015-01-08 11:13:06

10

如果兩個範圍進行測試(你定單元和你給定的範圍)並不在同一個Worksheet,然後Application.Intersect拋出一個錯誤。因此,辦法避免是像

Sub test_inters(rng1 As Range, rng2 As Range) 
    If (rng1.Parent.Name = rng2.Parent.Name) Then 
     Dim ints As Range 
     Set ints = Application.Intersect(rng1, rng2) 
     If (Not (ints Is Nothing)) Then 
      ' Do your job 
     End If 
    End If 
End Sub 
0

@ mywolfe02給出了一個靜態的範圍代碼,以便他INRANGE工作正常,但如果你想添加的動態範圍,然後用這一個與他INRANGE功能。當你想填充數據來修復開始單元格和最後一列也是固定的,這會更好。

Sub DynamicRange() 

Dim sht As Worksheet 
Dim LastRow As Long 
Dim StartCell As Range 
Dim rng As Range 

Set sht = Worksheets("xyz") 
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row 
Set rng = Workbooks("Record.xlsm").Worksheets("xyz").Range(Cells(12, 2), Cells(LastRow, 12)) 

Debug.Print LastRow 

If InRange(ActiveCell, rng) Then 
'  MsgBox "Active Cell In Range!" 
    Else 
     MsgBox "Please select the cell within the range!" 
    End If 

End Sub 
0

這裏是另一種選擇以查看是否範圍內存在的細胞。如果您像我一樣遇到Intersect解決方案問題。

If InStr(range("NamedRange").Address, range("IndividualCell").Address) > 0 Then 
    'The individual cell exists in the named range 
Else 
    'The individual cell does not exist in the named range 
End If 

InStr是一個VBA函數,用於檢查一個字符串是否存在於另一個字符串中。

https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/instr-function

相關問題