Excel VBA列B和C或列D需要

我有一个企业范围内使用的电子表格。 我试图把检查,以便某些领域是必需的。 具体而言,需要列B(姓)和C(名),或者列D(组织)是必需的。 但是,B,C和D不能全部填入。如果该行中有任何数据,则需要B和C或D.

我的想法是放入一个button来运行这个macros。 我可以做。

在这一点上我已经尝试了很多东西。 如果有人能提供任何见解,我可以包含电子表格。 我有一个在testing表上工作的macros,但是在这张表上不起作用,如果这样做会有所帮助的话。 这是macros

Sub CheckVal2() Dim ws As Worksheet Dim wsCurr As Worksheet Dim cel As Range Dim lngLastRow As Long Dim lngRow As Long For Each ws In Worksheets If Left$(ws.Name, 7) = "Current" Then Set wsCurr = ws Exit For End If Next With wsCurr lngLastRow = .Range("B5000").End(xlUp).Row For lngRow = 2 To lngLastRow For Each cel In .Range("B" & lngRow & ":E" & lngRow) If cel = "" Then MsgBox "First and Last Name or HCO must be populated." Cancel = True Exit Sub End If If cel <> "" Then If .Cells(lngRow, "D") = "" Then If .Cells(lngRow, "B") = "" Or _ .Cells(lngRow, "C") = "" Then MsgBox "First and Last Name or HCO must be populated." Cancel = True Exit Sub End If End If End If Next Next End With ' End Sub 

一旦你得到了什么导致错误试图访问wsCurr(我怀疑这只是工作表不存在的情况下),你应该修改你的代码,如下所示:

 With wsCurr lngLastRow = .Range("E5000").End(xlUp).Row For lngRow = 2 To lngLastRow 'First check whether first/last name has been consistently advised If (.Cells(lngRow, 2) = "") <> _ (.Cells(lngRow, 3) = "") Then MsgBox "Row " & lngRow & " - First Name and Last Name must both be advised or both be blank" Cancel = True ' I assume this is a global variable? Exit Sub End If 'Now check that last name has not been advised if HCO has been, and vice-versa If (.Cells(lngRow, 2) = "") = _ (.Cells(lngRow, 4) = "") Then MsgBox "Row " & lngRow & " - First and Last Name, or HCO, must be populated but not both." Cancel = True Exit Sub End If Next End With 

这将解决您的testing中存在的问题,根据我所知,这些问题不允许列出所有三列的情况。

我还更改了设置lngLastRow的列,因为如果它是根据列B设置的,并且数据的最后一行只包含列C和/或D中的值,那么最后一行不会正在testing。