在vba中更正多个if语句的顺序

时间:2013-10-08 21:00:59

标签: excel vba excel-vba

当$ A $ 5的值等于“Company 2”时,我需要此宏来隐藏某些列。下面的查询成功隐藏了列但未执行打印循环。设置它的正确方法是什么?

Sub PrintAll()

  Dim BrokerCell As Range
  Dim TotalCell As Range
  Dim Rng As Range
  Dim Wks As Worksheet

 Set Wks = Worksheets("PRINT PAGE")

 If Range("$A$5").Value = "Company 1" Then
  Set Rng = ThisWorkbook.Names("Company1").RefersToRange
 ElseIf Range("$A$5").Value = "Company 2" Then
  Set Rng = ThisWorkbook.Names("Company2").RefersToRange
 Else: Set Rng = ThisWorkbook.Names("Company3").RefersToRange
 End If

If Range("$A$5").Value = "Company 2" Then
    Columns("M:O").Select
    Selection.EntireColumn.Hidden = True
    Else: Columns("M:O").Select
    Selection.EntireColumn.Hidden = False

        For Each BrokerCell In Rng
            If BrokerCell <> "" And Range("$S$5").Value <> "" Then
            Wks.Range("$B$5").Value = BrokerCell.Text
            Wks.PrintOut
            End If
        Next BrokerCell

 End If

End Sub

2 个答案:

答案 0 :(得分:1)

您的For Each循环包含在Else语句的If Range("$A$5").Value = "Company 2" Then部分中。它仅在If语句求值为false时执行。

如果您需要在所有实例中执行For Each循环,请在End If之后移动它。如果仅在If语句求值为True时才需要执行,请在Else之前移动它。

答案 1 :(得分:0)

我相信这是你想要完成的,见下文。

Sub PrintAll()

Dim BrokerCell As Range
Dim TotalCell As Range
Dim Rng As Range
Dim Wks As Worksheet
Dim sCellValue As String

Set Wks = Worksheets("PRINT PAGE")
sCellValue = Replace(Range("$A$5").Value, " ", "")
    If sCellValue = "Company1" Then
        Set Rng = ThisWorkbook.Names(sCellValue ).RefersToRange
    ElseIf sCellValue = "Company2" Then
        Set Rng = ThisWorkbook.Names(sCellValue ).RefersToRange
    Else
        Set Rng = ThisWorkbook.Names("Company3").RefersToRange
    End If

    Columns("M:O").Select
    If sCellValue = "Company2" Then
        Selection.EntireColumn.Hidden = True
    Else
        Selection.EntireColumn.Hidden = False
    End If
    For Each BrokerCell In Rng
        If BrokerCell <> "" And Range("$S$5").Value <> "" Then
            Wks.Range("$B$5").Value = BrokerCell.Text
            Wks.PrintOut
        End If
    Next BrokerCell

End Sub