VBA excel如何检查单元格是否偏移,是指工作表内的单元格

我想检查一个小区有多less个邻居,都是空的。 当我不知道我的手机是否有8个邻居或者更less的时候,我该怎么做? 这是我的代码。 它只适用于我的单元格不在工作表的第一行或最后一行或列时。

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 

创build一个计算边界的数组,并用它来定义你的“邻居”单元块。

 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 

尝试下面的代码,你需要检查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