christhedonstar
Programmer
Hi,
Is there a way to copy the macros from one workbook into another using c#?
Thanks,
Chris
Is there a way to copy the macros from one workbook into another using c#?
Thanks,
Chris
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
using Microsoft.Vbe.Interop;
using System.Reflection;
using System.Runtime.InteropServices;
Excel.Application app = new Excel.ApplicationClass();
app.Visible = false;
string path1 = @"C:\oldModules.xls", path2 = @"C:\newModules.xls";
// open up the source and destination spreadsheets
Excel._Workbook wbSource = app.Workbooks.Open(path1, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value),
wbDestination = app.Workbooks.Open(path2, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
VBComponent dest = null, current = null;
// Iterate existing workbook and copy over the code modules
IEnumerator e = wbSource.VBProject.VBComponents.GetEnumerator();
e.Reset();
while(e.MoveNext())
{
current = (VBComponent)e.Current;
dest = wbDestination.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);
dest.CodeModule.AddFromString(current.CodeModule.get_Lines(1, current.CodeModule.CountOfLines));
dest.Name = current.Name;
wbDestination.Save();
Marshal.ReleaseComObject(dest);
Marshal.ReleaseComObject(current);
dest = null;
current = null;
}
e = null;
// save and close the updated workbook
wbDestination.Close(true, Missing.Value, Missing.Value);
app.Quit();
// release com objects
Marshal.ReleaseComObject(wbSource);
Marshal.ReleaseComObject(wbDestination);
Marshal.ReleaseComObject(app);