Excel vba 以编程方式将代码添加到工作表模块 [英] Excel vba add code to sheet module programmatically

查看:51
本文介绍了Excel vba 以编程方式将代码添加到工作表模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to put the programmatically generated workbook an event code similar to below:

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 模块中.

Use this to add a workbook and place a worksheet change event into the Sheet1 module.

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

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

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

Run the code again and it should work.

这篇关于Excel vba 以编程方式将代码添加到工作表模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆