我想查看一个小区的邻居是空的。 当我不知道我的手机是否有8个邻居或更少时,我该怎么做? 这是我的代码。它仅在我的单元格不在工作表的第一行或最后一行或列上时才有效。
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 :(得分:1)
尝试以下代码,您需要检查ActiveCell.Row
和ActiveCell.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
答案 1 :(得分:0)
创建一个计算边界的数组,并使用它来定义你的邻居块#39;细胞
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