按钮单击查找空单元格

时间:2015-10-29 16:29:05

标签: excel vba excel-vba

我是excel VBA的新手,并尝试创建一个表单让用户填写。我遇到循环问题,找不到单元格It is how the table look like 字段分为2红色和绿色。红色是必需单元格,绿色是可选字段。 如您所见,用户缺少一些必需的单元格。因此,我想为用户创建一个按钮,以便在检查后检查他们应该填写哪一个。我想强调丢失的单元格,以便他们知道他们填写了哪一个。It is the table should look like after clicking the check button

现在我的问题是我用于每个循环或循环找出丢失的单元格但我只能通过设置范围来找到这些单元格

dim rng As range 


Set rng = Range("B3:j10")

但它是用户填写表单这是一个动态工作表,我永远不会知道用户将填写多少数据。如果我使用我的代码,工作表将不停地突出显示所有空单元格。 我希望检查验证可以检测并突出强制(红色字段)缺少填充但不是所有空单元格。即使是新用户填写表单,检查按钮仍然可以正常工作

这是我的代码:

sub CommandButton1_click()

Dim rng As range 
Dim found, emptyCell

Set rng = Range("B3:J10")
emptyCell = IsEmpty(emptyCell)
found = false

For each emptyCell In rng
If emptyCell.Cells = "" Then
found = True
emptyCell.Interopr.ColorIndex = 6
Else 
emptyCell.Interopr.ColorIndex = 0
End If
End Sub

2 个答案:

答案 0 :(得分:2)

这应该这样做。

交叉函数测试两个范围是否交叉。如果他们没有交叉那么它什么都不做。

Sub CommandButton1_click()

Dim rng As Range
Dim found As Boolean, emptyCell As Range
Dim lastrow As Long

lastrow = Range("B3").end(xldown).row

Set rng = Range("B3:J" & lastrow)
'emptyCell = IsEmpty(emptyCell)
found = False

For Each emptyCell In rng
If Not Intersect(emptyCell, Range("B4:B" & lastrow & ",D4:E" & lastrow & ",H4:I" & lastrow)) Is Nothing Then
    If emptyCell.value = "" Then
        found = True
        emptyCell.Interior.ColorIndex = 6
    Else
        emptyCell.Interior.ColorIndex = 0
    End If
End If
Next
End Sub

答案 1 :(得分:0)

试试这个::)

Dim i As Byte
Dim rng As Range
Dim emptyCell As Range
For i = 3 To 10
  Set rng = Range(Cells(i, 2), Cells(i, 8))
  For Each emptyCell In rng
    If emptyCell = "" And Join(Application.WorksheetFunction.Index _
    (rng.Value, 1, 0)) <> "" And Cells(1, emptyCell.Column) _
    .Interior.ColorIndex = 3 Then
      emptyCell.Interior.ColorIndex = 6
      found = True
    Else
      emptyCell.Interior.ColorIndex = 0
    End If
  Next
Next

更改其他行的For i = 3 to 10

更改标题的颜色[red = true]以检查其他列

更改Set rng = Range(Cells(i, 2), Cells(i, 8))以更改已选中的列

相关问题