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

标签 vba excel

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

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

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

enter image description here

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

enter image description here

enter image description here

然后找到“Microsoft Visual Basic for Applications Extensibility 5.3 库”并选中它。

enter image description here

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

关于vba - Excel VBA以编程方式将代码添加到工作表模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837006/

相关文章:

.net - 如何优化这个简单但可怕的实现?

excel - 自动调整行高不起作用

vba - 使用可视文件选择器将每个工作表保存到单独的 xls 文件中的宏

python - openpyxl 导致 excel 中现有 DataValidation 丢失

excel - 如何使用矩阵填充 Excel 中的列表框?

excel - 显示 [h] :mm numberformat with comma separator for thousands of hours

vba - 在 ThisWorkbook 中编辑脚本时 Excel 崩溃

Excel VBA : how do I call VLOOKUP if condition is met?

excel - Excel VBA Vlookup复制其他表中不存在的条目的先前条目数据

c# - Excel 2010 com 对象引用未发布