打开工作表时自动执行的宏

时间:2014-02-05 13:24:27

标签: excel vba excel-vba

每次打开excel文件时,我的宏(update())是否可能自动执行。下面的代码不能很好地工作。感谢

Private Sub Workbook_Open()

    Run "update"

End Sub

Option Explicit

Sub update()

    Dim rng As Range
    Dim Sh As String, Cl As String
    Dim ws As Worksheet
    Dim i As Integer, ncol As Integer
    Dim Row1 As String

    ncol = Range("B1:O1").Columns.Count

    For i = 1 To ncol
        Set ws = ThisWorkbook.Sheets("sheet1")

        With ws
            Row1 = .Cells(1, i).Value

            If Len(Row1) > 0 Then
                Sh = Split(Row1, "'!")(0)
                Cl = Split(Row1, "'!")(1)
                Set rng = ThisWorkbook.Sheets(Sh).Range(Cl)

                'Here you were always refering to cell A2 not moving through the values which was the main problem.
                rng.Value = .Cells(2, i).Value
            End If
        End With
    Next i
End Sub

1 个答案:

答案 0 :(得分:3)

如评论中所述。移动以下内容:

Private Sub Workbook_Open()

    Run "update"

End Sub

到这里:

enter image description here

正如Siddharth所提到的,还有另一种方法可以让宏在文件打开事件上运行,这只是为了给它以下签名:

Sub Auto_Open

另外,我个人可能不会将子程序称为“更新”,因为它非常接近于许多保留字 - 我会选择像“updateSomething”这样的东西。这只是个人选择。

相关问题