2017-05-06 46 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

相关问题