Excel vba以编程方式将代码添加到工作表模块

时间:2016-01-17 09:47:01

标签: excel vba excel-vba

如何将以编程方式生成的工作簿放入类似于下面的事件代码:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim nextTarget As Range

    Set nextTarget = Range(Selection.Address) 'store the next range the user selects

    Target.Columns.Select 'autofit requires columns to be selected
    Target.Columns.AutoFit

    nextTarget.Select
End Sub

1 个答案:

答案 0 :(得分:15)

使用此选项添加工作簿并将工作表更改事件放入Sheet1模块。

Sub AddSht_AddCode()
    Dim wb As Workbook
    Dim xPro As VBIDE.VBProject
    Dim xCom As VBIDE.VBComponent
    Dim xMod As VBIDE.CodeModule
    Dim xLine As Long

    Set wb = Workbooks.Add

    With wb
        Set xPro = .VBProject
        Set xCom = xPro.VBComponents("Sheet1")
        Set xMod = xCom.CodeModule

        With xMod
            xLine = .CreateEventProc("Change", "Worksheet")
            xLine = xLine + 1
            .InsertLines xLine, "  Cells.Columns.AutoFit"
        End With
    End With

End Sub

当您第一次运行代码时,您可能会收到错误。

enter image description here

点击停止图标并选择工具菜单和“参考”

enter image description here

enter image description here

然后找到“Microsoft Visual Basic for Applications Extensibility 5.3 library”并检查它。

enter image description here

再次运行代码,它应该可以工作。