0

当 $A$5 的值等于“公司 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
4

2 回答 2

1

您的For Each循环包含在语句的Else部分中。If Range("$A$5").Value = "Company 2" Then它只会在该If语句评估为假时执行。

如果您需要For Each在所有实例中执行循环,请将其移到End If. 如果您需要它仅在If语句评估为时执行True,则将其移至Else.

于 2013-10-08T21:07:03.927 回答
0

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

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
于 2013-10-08T21:10:51.180 回答