Excel工作簿打开时自动运行两个vba代码

时间:2019-03-12 22:25:21

标签: excel vba

我有两个要在打开Excel工作簿时运行的VBA代码。

Sub test2()
    Dim c As Range
    For Each c In Range("A1:A1").Cells
        c.Select
        SendKeys "{F2}", True
        SendKeys "{ENTER}", True
    Next
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCell As Range
    If Target.Address <> Range("A1").Address Then Exit Sub
    Application.ScreenUpdating = False
    For Each xCell In Range("B3:P3")
        xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
    Next
    Application.ScreenUpdating = True
End Sub

它可以手动完美运行。

我已经尝试过Sub Workbook_Open,但是它不起作用。 我也在模块,工作表和ThisWorkbook中进行了尝试。 当工作簿打开时,无法使其自动工作。

该代码应该按F2键并输入单元格A1,然后根据A1中的值隐藏一些列。

我以这种方式修改了代码:

Private Sub Workbook_Open()
     test2
End Sub
Sub test2()
    Dim c As Range
    For Each c In Sheets("MySheet").Range("A1:A1").Cells
        c.Select
        SendKeys "{F2}", True
        SendKeys "{ENTER}", True
    Next
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCell As Range
    If Target.Address <> Range("A1").Address Then Exit Sub
    Application.ScreenUpdating = False
    For Each xCell In Range("B3:P3")
        xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
    Next
    Application.ScreenUpdating = True
End Sub

打开工作表时,它开始执行,执行第一部分(F2 + Enter),但在此停止。不执行此部分:

Private Sub Worksheet_Change(ByVal Target As Range)

        Dim xCell As Range
        If Target.Address <> Range("A1").Address Then Exit Sub
        Application.ScreenUpdating = False
        For Each xCell In Range("B3:P3")
            xCell.EntireColumn.Hidden = (xCell.Value < Target.Value)
        Next
        Application.ScreenUpdating = True
    End Sub

在Sheet1(不是“ ThisWorkbook”)中手动编写的代码运行良好(不是自动)。

打开文件时,“ ThisWorkbook”中写入的相同代码会自动执行,但中间会停止(如前所述)。

0 个答案:

没有答案