VBA 2 IF条件适用于列

这是我的第一篇文章,请耐心等待,如果我正在做/错误的问题。 我的问题是:我有2列,A是孩子的数量,B是这些孩子的名字。 这些值是手动input的,我只是想要B是强制性的,如果A填充。 这是我的想法:

Private Sub Workbook_BeforeClose(Cancel As Boolean) If Not IsEmpty(Sheet1.Range("A1")) Then If IsEmpty(Sheet1.Range("B1")) Then MsgBox "Please fill in cell B1 before closing." Cancel = True Else ' End If End If End Sub 

这实际上是完美的工作,不幸的是,我不能设法扩展它的整个列,用A1代替A1:A1000和B1,例如B1:B1000,它不起作用。

我如何validation整个列A和B?

提前致谢!

尝试这个

 Private Sub Workbook_BeforeClose(Cancel As Boolean) Cancel = Evaluate("SUMPRODUCT(--(ISBLANK(Sheet1!B:B) <> ISBLANK(Sheet1!A:A)))") If Cancel Then MsgBox "Please fill in column B before closing." End Sub 

编辑

为了将用户带到数据丢失的地方,并考虑到您提供的有关数据的附加信息,请尝试以下操作:

 'Private Sub Workbook_BeforeClose(Cancel As Boolean) Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Dim r: r = Evaluate( _ "MATCH(FALSE, ISBLANK('ELENCO AGGIORNATO'!V:V) = ISBLANK('ELENCO AGGIORNATO'!W:W), 0)") If IsError(r) Then Exit Sub ' All is fine Cancel = True Application.Goto Sheets("ELENCO AGGIORNATO").Cells(r, "V").Resize(, 2) msgBox "Please fill missing data before saving." End Sub 

另外请注意,我build议使用Workbook_BeforeSave而不是Workbook_BeforeClose ,因为如果用户决定放弃他(不完整)的工作并closures工作簿而不保存,则没有任何影响。

你可以尝试这样的事情…

 Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim str As String Dim Rng As Range, Cell As Range Dim FoundBlank As Boolean Set Rng = Sheet1.Range("A1:A1000") str = "Please fill the cells listed below before colsing..." & vbNewLine & vbNewLine For Each Cell In Rng If Cell <> "" And Cell.Offset(0, 1) = "" Then FoundBlank = True str = str & Cell.Address(0, 1) & vbNewLine End If Next Cell If FoundBlank Then Cancel = True MsgBox str, vbExclamation, "List of Blank Cells Found!" End If End Sub