使用Worksheet_Activate()时Excel VBA没有screenupdate

时间:2018-10-16 10:12:32

标签: excel vba worksheet

我创建了一个宏,该宏根据输入工作表折叠一定数量的列。当用户激活工作表时,该宏正在运行,如下所示。

Worksheet_Activate宏:

Private Sub Worksheet_Activate()
ActiveSheet.Unprotect "mypassword"

Call collapsecolumns

ActiveSheet.Protect "mypassword"

End sub

名为的宏:

Public Sub collapsecolumns()

Dim ws1 As Worksheet: Set ws1 = Sheets("inputSheet")
Dim ws2 As Worksheet: Set ws2 = ActiveSheet
Dim sheetNo As Integer, colToCollapse As Integer

'number in sheet name define range for counting columns to collapse
sheetNo = Right(ws2.Name, 1) 

'input range differs depending on which sheet is chosen
colToCollapse = Application.WorksheetFunction.CountA(ws1.Range("J" & ((6 * sheetNo) - 4) & ":J" & ((6 * sheetNo) + 1)))

ws2.Range(Cells(1, 1), Cells(1, 35)).EntireColumn.Hidden = False

If colToCollapse = 0 Then
    Exit Sub
End If

ws2.Range(Cells(1, colToCollapse * 6), Cells(1, 35)).EntireColumn.Hidden = True

End Sub

但是,激活工作表后,您看到的列会折叠(或折叠),具体取决于您在另一张表中写的内容。我用ScreenUpdate = False和EntireEvents = False的各种组合和放置来掩盖崩溃,但没有成功

在使用Worksheet_Activate()折叠列时,有没有办法让用户首先看到工作表?

1 个答案:

答案 0 :(得分:0)

我添加了两行代码,以便用户可以在隐藏列时查看

SELECT t1.year_no,
       t1.month_name,
       @early := @endst                             AS EarlyStock,
       @prod := t1.production                       AS production,
       @dead := t1.dead                             AS dead,
       ( @early + @prod - @dead )                   AS LivePlant,
       @dist := t1.distri                           AS Distri,
       @endst := ( @early + @prod - @dead - @dist ) AS EndStock
FROM   (SELECT Coalesce(Year(trans.date_trans), Year(CURRENT_DATE())) AS year_no,
               Coalesce(Month(trans.date_trans), mon.id_month) AS month_no,
               mon.month_name,
               Coalesce(Sum(trans.production_plant), 0)    AS production,
               Coalesce(Sum(trans.dead_plant), 0)          AS dead,
               Coalesce(Sum(trans.distribution_plant), 0)  AS Distri
        FROM   tb_month AS mon
               LEFT JOIN tb_transaction AS trans
                      ON Month(trans.date_trans) = mon.id_month
        GROUP  BY year_no,
                  month_no,
                  mon.month_name
        ORDER  BY year_no,
                  month_no) AS t1
       CROSS JOIN (SELECT @prod := 0,
                          @dead := 0,
                          @dist := 0,
                          @early := 0,
                          @endst := 0) AS user_init_vars  

它将首先将excel工作表移至将隐藏的列 然后将等待1秒钟,然后隐藏列

我希望这就是您想要的...