无法让 For Each 循环包含多个 If 函数

问题描述 投票:0回答:1

我正在为工作簿中的 36 张写一个长代码。我的目标是在用户执行“另存为”之前填写特定的单元格。我的代码适用于第一张纸,因为我在代码中单独编写了每个必需的框。但是其他35张都是一样的(这是现场技术人员正在测试的设备,每张都是一个设备,每个客户有不同数量的设备)。在这 35 张纸上单独编写每个框,代码变得很大。

所以我正在尝试一个 For Each 工作表循环并只编写一次代码,但它似乎无法以这种方式工作。我确定我在我的代码中遗漏了一些东西,但我盯着它看的时间太长了,无法弄清楚。任何建议将不胜感激。

以下是我的部分代码:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name Like "BF" Then
       If Cells(17, 5) = "Reduced Pressure" And Cells(29, 5) = "" Then
          MsgBox "CHECK #1 missing value on Worksheets.Name", vbExclamation, "Dignity Fire Protection"
          Cancel = True
          Application.Goto Cells(29, 5)
        End If
     
       If Cells(17, 5) = "Reduced Pressure" And Cells(31, 5) = "" Then
          MsgBox "CHECK #2 missing value Worksheets.Name", vbExclamation, "Dignity Fire Protection"
          Cancel = True
          Application.Goto Cells(31, 5)
         End If
     
excel vba
1个回答
0
投票

试试这个:

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name Like "BF" Then
        If Cells(17, 5) = "Reduced Pressure" Then
            If Cells(29, 5) = "" Then
                MsgBox "CHECK #1 missing value on Worksheets.Name", vbExclamation, "Dignity Fire Protection"
                Cancel = True
                Application.Goto Cells(29, 5)
            ElseIf Cells(31, 5) = "" Then
                 MsgBox "CHECK #2 missing value Worksheets.Name", vbExclamation, "Dignity Fire Protection"
                 Cancel = True
                 Application.Goto Cells(31, 5)
            End If
        End If
    Next ws
© www.soinside.com 2019 - 2024. All rights reserved.