2

I have been looking into using VBA to write VBA Code. So that ultimately I can write an algorithm to write loops depending on a variable entered.

I have come across the below, which looks as if it will add code to the VBA project but I am missing something for it to work. Struggling to find anything on this. I know that 'ThisWorkbook' is the issue. Any ideas to what I need to call it to be able to reference that sheet (same name) in the VBA project.

Thanks

Option Explicit

Sub test()

Dim WB_Write_Code_Test As Workbook
Dim WS_Test As Worksheet
Dim nextline As Long

Set WB_Write_Code_Test = Workbooks.Open("Write Code Test")

Set WS_Test = WB_Write_Code_Test.Sheets("Test")

With ActiveWorkbook.VBProject. _
VBComponents(ThisWorkbook).CodeModule

nextline = .CountOfLines + 1

.InsertLines nextline, WS_Test.Cells(1, 1).Value
End With

End Sub
5
  • 1
    You could write a vba module then import it into the workbook, or generate the code in the Console then copy/paste it. I don't think it's a good idea to write vba code for writing vba code... sounds strange. Commented Aug 28, 2017 at 14:51
  • what is the specific failure you're having? Is ThisWorkbook the same as ActiveWorkbook? Commented Aug 28, 2017 at 14:51
  • So the idea is that the code will run and add code depending on the variables. I can just delete it all and replace with original code at the end. (saves me creating the code and then copying & paste and then running it?) The specific issue (I think) is the ThisWorkbook. ThisWorkbook refers to the VBA Project sheet I am writing code into. ActiveWorkbook is the excel doc itself. Commented Aug 28, 2017 at 14:59
  • Or if I wanted a code that could 'learn' I would need it to be able to write code directly Commented Aug 28, 2017 at 15:12
  • Be aware you need to specifically allow access to VBProject using VBA in the Excel macro options. Commented Aug 28, 2017 at 15:53

1 Answer 1

1

Thanks, That has done it.

For reference the missing code is:

VBComponents(ThisWorkbook.CodeName).CodeModule
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.