当另一个单元格具有特定值时,如何在Excel中要求输入列?

时间:2016-08-16 19:04:59

标签: excel vba

我有一个电子表格,其中包括学生姓名,种族/民族,性​​别,学位,专业,状态,年份开始以及毕业后的职业生涯。感谢那些帮助我使用我的代码的人,如果在A栏中提供学生姓名,则需要输入种族/种族,性别和学位。现在我需要做一些额外的事情。如果F列中Status的值为“Graduated”,我也希望填写毕业后职业栏(H栏)。下面列出了我能提出的最接近的代码,现在我遇到了问题。

当F列中的状态具有“分级”值时,Excel不仅要求用户在H列中填写职业毕业后的职业,还要求其他列。我应该如何修改代码,因此只需要H列?

谢谢!

Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim rngCell As Range, strBlanks As String

Application.ScreenUpdating = False

strBlanks = vbNullString
For Each rngCell In Worksheets("Sheet1").Range("F2:F20").Cells
If rngCell.Value = "Graduated" Then
If WorksheetFunction.CountA(rngCell.Offset(0, 2).Resize(1, 1)) < 1 Then
strBlanks = strBlanks & IIf(Len(strBlanks) > 0, ",", "") & _
Replace(rngCell.Offset(0, 2).Resize(1,1).SpecialCells(xlCellTypeBlanks).Address, "$", "")
End If
End If
Next

If Not strBlanks = vbNullString Then
MsgBox "Entries required in cells " & vbCrLf & vbCrLf & strBlanks
Cancel = True
Exit Sub
End If
End Sub

2 个答案:

答案 0 :(得分:0)

为什么要使用以下内容?

&安培; vbCrLf&amp; vbCrLf

似乎你的代码工作得很好,但是这些两个变量如何被其他列填充。

此外,除了H之外,哪些列还会返回?什么时候应该提示用户输入值?

答案 1 :(得分:0)

您可以使用Autofilter来避免循环遍历单元格并进行一次性操作

Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim toBeFilledAddress  As String

    With Worksheets("Sheet1") '<--| '<-- change "Sheet1" with your actual sheet name
        With .Range("A1:H" & .Cells(.Rows.Count, 1).End(xlUp).Row) '<--| reference its range in columns A:B from row 1 to column "A" last non empty cell row
            .AutoFilter field:=6, Criteria1:="Graduated" '<--| filter referenced range on its 6th column with "Graduated"
            .AutoFilter field:=8, Criteria1:="" '<--|filter referenced range again on its 8th column with blanks
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then toBeFilledAddress = .Offset(1, 7).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible).Address(False, False)  '<--| store all matching cells address
        End With
        .AutoFilterMode = False '<--| show all rows back
    End With

    If toBeFilledAddress <> "" Then '<--| if any cell other than header ones has been filtered...
        MsgBox "Entries required in cells " & vbCrLf & vbCrLf & toBeFilledAddress
        Cancel = True
        Exit Sub '<--| this line could be avoided unless you're planning to add more lines after "End If"
    End If
End Sub