Excel VBA如果行有数据,单元格不能为空

我已经search这个答案,但不能完全find我所需要的。 我有一个用户将粘贴数据的文档,有时可达5000行(这是限制)。 它有专栏A-AG。 有些列是必需的,有些则不是。 我被告知用户可能会发布空白行的数据。

我正在尝试使用macros来提醒用户缺less数据。 我将把它绑定到一个用户表单框。 我想要解决这个问题的方式是循环遍历从19(数据开始的位置)到5000的行。如果该行有任何数据,则检查所需的列。

例如,检查第19行,如果有任何数据,请检查F列。如果F列中的数据丢失,则生成消息Box。 我希望这是有道理的,任何帮助将不胜感激。

下面的代码将检查19到5000中的每一行,看前面33列(即A到AG)是否有非空单元格,然后检查某些单元格是否为空。 (我任意决定F,G,J栏是强制性的。)

Sub CheckRows Dim r As Long Dim c As Long 'Dim emptyRow As Boolean With ActiveSheet For r = 19 to 5000 'Edited based on suggestion by Scott Craner If WorksheetFunction.CountA(.Range(.Cells(r, 1), .Cells(r, 33))) > 0 Then 'emptyRow = True 'For c = 1 To 33 ' If Not IsEmpty(.Cells(r, c)) Then ' emptyRow = False ' Exit For ' End If 'Next 'If Not emptyRow Then If IsEmpty(.Cells(r, "F")) Or _ IsEmpty(.Cells(r, "G")) Or _ IsEmpty(.Cells(r, "J")) Then MsgBox "Row " & r & " has some compulsory cells not filled in" End If End If Next End With End Sub 

其他答案是有效的,但是由于关键规则被颠倒了,效率不高。 没有理由检查一行是否为空, 除非有一个必填字段丢失 。 从你的问题来看,这个规则是:

行必须包含所有必填字段,除非它们是空的。

这可以重申为:

如果任何必填字段为空,则整行必须为空。

第二个编程testing的效率要高得多,因为如果testing的第一部分是真的,你可以短路:

 Sub CheckRows() Dim r As Long, c As Long, missingValue As Boolean With ActiveSheet For r = 1 To 5000 Select Case True Case .Cells(r, "F") = vbNullString: missingValue = True Case .Cells(r, "G") = vbNullString: missingValue = True Case .Cells(r, "J") = vbNullString: missingValue = True Case Else missingValue = False End Select 'This is the ONLY CASE where you need to check if the row is empty. If missingValue Then If WorksheetFunction.CountA(.Range(.Cells(r, 1), .Cells(r, 33))) > 0 Then MsgBox "Row " & r & " has some compulsory cells not filled in" End If End If Next End With End Sub 

尝试首先检查一行中的所有单元格,如果find任何数据,则检查所需的项目。 像这样(我的VBA很生锈,所以这可能不是可复制的,但它应该是接近的):

 Dim row As Integer, col As Integer, hasData As Boolean Dim errors() As String, errorText as String ReDim errors(1 To 1) As String For row = 19 To 5000 hasData = False ` Check each cell in this row to see if it has data For col = 1 To 33 If IsEmpty(Cells(row, col).Value) = True Then hasData = True Exit For End If Next col If hasData Then errorText = "" `validate data here for this row `set errorText to non-empty if an error found If errorText <> "" Then errors(UBound(errors)) = errorText ReDim Preserve errors(1 To UBound(errors) + 1) As String End If End If Next row `if errors found, join all the errors together and show to user If UBound(errors) > 1 Then MsgBox Join(errors, vbCrLf)