Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy VBA code from a Sheet in one workbook to another?

Tags:

excel

vba

vbe

I've been using the lines below to compy VBA modules from one workbook to another and I don't know if there is an easier way, but they have been working fine:

Set srcVba = srcWbk.VBProject
Set srcModule = srcVba.VBComponents(moduleName)

srcModule.Export (path) 'Export from source
trgtVba.VBComponents.Remove VBComponent:=trgtVba.VBComponents.Item(moduleName) 'Remove from target
trgtVba.VBComponents.Import (path) 'Import to target

However now I need to copy VBA code that is in a Sheet, not in a Module. The above method doesn't work for that scenario.

What code can I use to copy VBA code in a sheet from one workbook to another?

like image 229
user1283776 Avatar asked Aug 28 '13 20:08

user1283776


People also ask

How do I copy VBA code from one sheet to another?

Open both the workbook that contains the macro you want to copy, and the workbook where you want to copy it. On the Developer tab, click Visual Basic to open the Visual Basic Editor. , or press CTRL+R . In the Project Explorer pane, drag the module containing the macro you want to copy to the destination workbook.

Can you copy data from one worksheet to another using a VBA program?

Copying data with VBA is a common process solved with well written code. Lets say we want to copy data from Sheet1 to Sheet2 with the help of code on a regular basis. The following Excel VBA procedure copies data from the active sheet and pastes it in the first blank cell at the bottom of a range in another worksheet.

How do I jump from one sheet to another in Excel VBA?

If your workbook contains a lot of sheets then you can right-click the tab navigation buttons to see a list of all visible sheets. You can then double-click a sheet in the list to jump to it.


1 Answers

You can't remove and re-import the VBComponent, since that would logically delete the whole worksheet. Instead you have to use CodeModule to manipulate the text within the component:

Dim src As CodeModule, dest As CodeModule

Set src = ThisWorkbook.VBProject.VBComponents("Sheet1").CodeModule
Set dest = Workbooks("Book3").VBProject.VBComponents("ThisWorkbook") _
    .CodeModule

dest.DeleteLines 1, dest.CountOfLines
dest.AddFromString src.Lines(1, src.CountOfLines)
like image 70
Chel Avatar answered Sep 28 '22 08:09

Chel