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 

使用它来添加工作簿并将工作表更改事件放置到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 

当你第一次运行代码时,你可能会得到一个错误。

在这里输入图像说明

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

在这里输入图像描述

在这里输入图像描述

然后find“Microsoft Visual Basic for Applications Extensibility 5.3库”并检查它。

在这里输入图像描述

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