1

I am fairly new to using VBA in Excel but I was wondering is there a way to run multiple codes at the same time?

My goal is to do a few things, First I need to insert a column, then add a column header, then add a formula to the cell beneath and copy the formula for all rows.

so far I have this code to run to input the row and then the header, but it won't work unless i run them each separately. is there a text I need to input to combine them so when I run it it just runs the whole thing at once? Thank you!

Sub AddColumns()

Worksheets(1).Range("AH1").EntireColumn.Insert

End Sub

Sub AddHeader()

    Worksheets(1).Range("AH1").Formula = "Group A"

End Sub
braX
  • 11,506
  • 5
  • 20
  • 33
Jumana
  • 11
  • 1
  • 2
  • 1
    Perhaps I'm misunderstanding, but you have shown two `Sub`routines. Couldn't you just call those subroutines from the main program? VBA might not have the notion of a main, but there is `Call` for chaining `Sub`s. Maybe this is what you want. –  Nov 16 '18 at 20:18
  • Possibly a duplicate: https://stackoverflow.com/q/16763112/1531971 –  Nov 16 '18 at 20:22
  • Possible duplicate of [Calling a Sub in VBA](https://stackoverflow.com/questions/7715044/calling-a-sub-in-vba) – Matt Ke Nov 16 '18 at 20:48
  • Jumana, If i understand your question, you need to know how to combine each action under one sub. Well, that is the purpose of VBA. I would suggest that you complete a basic vba course on line, there are many and basic vba training is usually free; One course is [here](https://www.udemy.com/topic/excel-vba/). You can also do Google searches for `online excel vba courses` and also search Google for what you are trying to accomplish and research how other people accomplish similar task. You can then try to combine your task and when/if you have a problem, ask a specific question on SO. – GMalc Nov 16 '18 at 22:40
  • 1
    Additionally, In answer to your title; No, VBA is single-threaded (one task must complete before another can run); you can't have two macros running at the same time. The workaround is you will have to use `DoEvents` to allow another macro to run. VBA `DoEvents` yields execution of your macro, so your computer processor will be able to simultaneously run other tasks and events. – GMalc Nov 16 '18 at 23:29

2 Answers2

3

What you are asking for (run multiple macros at the same time) is called multi-threading, but it's not what you want.

Try putting all your lines in one sub:

Sub AddColumnsAndHeaders()

Worksheets(1).Range("AH1").EntireColumn.Insert
Worksheets(1).Range("AH1").Formula = "Group A"

End Sub
cybernetic.nomad
  • 6,100
  • 3
  • 18
  • 31
3

Another method is to simply call them both from another routine.

Sub Main()

    AddColumns
    AddHeader

End Sub

Sub AddColumns()

    Worksheets(1).Range("AH1").EntireColumn.Insert

End Sub

Sub AddHeader()

    Worksheets(1).Range("AH1").Formula = "Group A"

End Sub  
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43