如何将以编程方式生成的工作簿放入类似于以下的事件代码:
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
当您第一次运行代码时,您可能会收到错误。
点击停止图标并选择工具菜单和“引用”
然后找到“Microsoft Visual Basic for Applications Extensibility 5.3 库”并选中它。
再次运行代码,它应该可以工作。
关于vba - Excel VBA以编程方式将代码添加到工作表模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837006/