2017-05-06 45 views
1

我想檢查單元格中有多少個鄰居爲空。 如果我不知道我的手機是否有8個鄰居或更少,我該怎麼做? 這是我的代碼。它只適用於我的單元格不在工作表的第一行或最後一行或列。VBA excel如何檢查單元格的偏移量是否指工作表內的單元格

Sub neighbors() 
Dim count%, i%, j% 
count = 0 
For i = -1 To 1 
    For j = -1 To 1 
     If VBA.IsEmpty(ActiveCell.Offset(i, j)) Then count = count + 1 
    Next j 
Next i 
' If activecell is empty - don't count it 
If VBA.IsEmpty(ActiveCell) Then count = count - 1 
MsgBox count 
End Sub 
+0

我不明白你的意思是'鄰居',但.CurrentRegion屬性(可能受限於Intersect)的工作? – Jeeped

+0

鄰居是圍繞單元格的8個單元格,除非單元格位於第一行或最後一行或列中,在這種情況下,鄰居較少。 CurrentRegion屬性不起作用,因爲相鄰的單元格可能是空的,或者有些可能是空的,有些是完整的,所以您無法預測當前區域會是什麼。 – hil

+0

請注意,我對以下編碼答案做了一些小調整。 – Jeeped

回答

0

創建計算邊界的數組,並用它來定義你的「鄰居」細胞塊。

Option Explicit 

Sub neighbors() 
    Dim n As Long, bounds As Variant 

    With ActiveCell 
     bounds = Array(Application.Max(1, .Row - 1), _ 
         Application.Max(1, .Column - 1), _ 
         Application.Min(.Parent.Rows.count, .Row + 1), _ 
         Application.Min(.Parent.Columns.count, .Column + 1)) 
    End With 
    With ActiveCell.Parent 
     With .Range(.Cells(bounds(0), bounds(1)), .Cells(bounds(2), bounds(3))) 
      Debug.Print .Address(0, 0) 
      n = Application.CountBlank(.Cells) + CBool(IsEmpty(ActiveCell)) 
     End With 
    End With 

    MsgBox n 
End Sub 
1

嘗試下面的代碼,你需要檢查ActiveCell.RowActiveCell.Column,看看他們是首當其衝。

代碼

Option Explicit 

Sub neighbors() 

Dim count As Long, i As Long, j As Long 
Dim firstRow As Long, FirstCol As Long 

count = 0 
If ActiveCell.Row < 2 Then '<-- first row 
    firstRow = 0 
Else 
    firstRow = -1 
End If 
If ActiveCell.Column < 2 Then '<-- first column ("A") 
    FirstCol = 0 
Else 
    FirstCol = -1 
End If 

For i = firstRow To 1 
    For j = FirstCol To 1 
     If IsEmpty(ActiveCell.Offset(i, j)) Then count = count + 1 
    Next j 
Next i 

' If activecell is empty - don't count it 
If IsEmpty(ActiveCell) Then count = count - 1 
MsgBox count 

End Sub 
+0

在這個解決方案中,還需要檢查最後一行或一列。 – hil

+0

@hil爲什麼?你打算使用ActiveCell行> 65000東西? –

+0

理論上,是的。是否有一個常數可以用來了解最後一行和最後一列的編號?我不是說「結束」。 – hil

相關問題