需要Excel VBA列B和C或列D.

时间:2016-08-30 22:13:56

标签: excel excel-vba excel-2010 vba

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

我的想法是输入一个按钮来运行这个宏。我能做到。

此时我已尝试过很多东西。我可以包含电子表格,以防任何人提供任何见解。我有一个在测试表上工作的宏,但是在这个工作表上不起作用,如果这有用的话。 这是宏

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

1 个答案:

答案 0 :(得分:1)

一旦你越过任何导致错误的尝试访问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

这将解决您的测试存在的问题,(据我所知)并不允许所有三列都被建议的情况。

我还更改了设置lngLastRow的列,因为如果它是基于列B设置的,并且数据的最后一行只包含C列和/或D列中的值,那么最后一行(s )不会被测试。