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
Insert VBA code to Excel Workbook Right-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.) and paste it to the right pane of the VBA editor ("Module1" window).
Actually, I need a macro (Personal.XLSB) that add a VBA module & write code in ThisWorkbook for any new worksheet. By any of the following way: 1. The module is saved and just need to import to the new sheet. Code need to be wrttin automatically to ThisWorkbook. 2. Code for the module need to be writin in into new module.
Different Ways to Add New Sheets in a Workbook using a VBA Code. 1. Add a Single Sheet. To add a single sheet, you can use the below code, where you didn’t specify any argument. This code tells Excel to add a sheet ... 2. Add Multiple Sheets. 3. Add a Sheet with a Name. 4. Add a Sheet with a Name ...
The module is saved and just need to import to the new sheet. Code need to be wrttin automatically to ThisWorkbook. 2. Code for the module need to be writin in into new module. Code need to be wrttin automatically to ThisWorkbook. This is to make the new worksheet run backup automatically. Here is the model and vba for you guys to use.
The modules are located in the Modules folder within the workbook. Sheet Modules – Each sheet in the workbook has a sheet object in the Microsoft Excel Objects folder. Double-clicking the sheet object opens its code module where we can add event procedures (macros).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With