I have many excel files (approx 200) in which I have to add VBA code (in the Workbook_Open()
method).
I would like to automate that, is there a way to add VBA code to an excel sheet programmatically?
Maybe with python's win32
package?
You do not need python for this.
Logic
.CreateEventProc
to write to the relevant code section. More about .CreateEventProc
HERE
Basic Requirements
You need to enable access to Visual Basic projects.
Trust access to the VBA project object model
to enable access to Visual Basic Projects.Code
Option Explicit
Sub Sample()
Dim VBP As Object, VBC As Object, CM As Object
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\routs\Desktop\Sample.xlsm")
Set VBP = wb.VBProject
Set VBC = VBP.VBComponents("ThisWorkbook")
Set CM = VBC.CodeModule
With VBC.CodeModule
.InsertLines Line:=.CreateEventProc("Open", "Workbook") + 1, _
String:=vbCrLf & _
" Debug.Print ""This is a sample text"""
End With
'wb.Close (True)
End Sub
Is there a way to programmatically copy code from one sheet except paste into a specific location of the code in the new sheet?
Basically what I'm trying to accomplish:
I have a couple of conditional formatting rules that I only want to be applicable after I've pressed a keyboard shortcut. I want to still be able to use the undo stack up to a certain point.
This code allows the particular conditional formatting to work the way I want it to, and is the only code on Sheet2:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With ThisWorkbook.Names("CurrentRow")
.Name = "CurrentRow"
.RefersToR1C1 = "=" & ActiveCell.Row
End With
End Sub
This is what I have for the code to run the copy
Sub CondFormat()
'
' CondFormat Macro
'
' Keyboard Shortcut: Ctrl+Shift+C
'
Dim CodeCopy As VBIDE.CodeModule
Dim CodePaste As VBIDE.CodeModule
Dim numLines As Integer
Set CodeCopy = ActiveWorkbook.VBProject.VBComponents("Sheet2").CodeModule
Set CodePaste = ActiveWorkbook.VBProject.VBComponents("Sheet4").CodeModule
numLines = CodeCopy.CountOfLines
If CodePaste.CountOfLines > 1 Then CodePaste.DeleteLines 1, CodePaste.CountOfLines
CodePaste.AddFromString CodeCopy.Lines(1, numLines)
End Sub
Below is the end bits of the Sheet 4 code. I don't want to delete everything on this new sheet, I would want it to appear under "Private Sub Worksheet_SelectionChange(ByVal Target As Range)" :
...
SendKeys "{TAB}", 1
SendKeys "{TAB}", 1
SendKeys "^{v}", 2
Application.Wait (Now + TimeValue("00:00:02"))
SendKeys "{F8}", 1
Application.Wait (Now + TimeValue("00:00:02"))
Loop
SendKeys "{NUMLOCK}", 1
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
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