Click here to Skip to main content
15,923,120 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I there any way to add a macro programmatically to a doc(Word) document and then save it?


What I have tried:

Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();
newApp.Visible = false;
object Unknown = Type.Missing;
var Source = filePath;
var doc = newApp.Documents.Open(Source);

var project = doc.VBProject;
var module = project.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule);

var macro = @"
Public Sub DoKbTest()
MsgBox ""Hello""
End Sub

Public Sub DoKbTestWithParameter(ByVal msg As String)
MsgBox msg
End Sub
";
module.CodeModule.AddFromString(macro);
//module.CodeModule.AddFromFile(vba);
newApp.Run("DoKbTest");
doc.SaveAs(finaldoc);
Posted
Updated 26-Oct-20 4:07am
v2
Comments
ZurdoDev 16-Oct-20 14:01pm    
See if you can record a macro creating a macro and then you'll have your answer.
CyberSecII 26-Oct-20 10:08am    
ok i found a way to do that but now i want to save my document but with my code it saves the document but the macro is missing.
Slacker007 26-Oct-20 11:10am    
I thought there was a file extension for word that indicates that this is a word document with macros? been almost 10 years since I worked with Word automation and macros, etc.
CyberSecII 1-Nov-20 1:58am    
Thank you Slacker007 for taking the time to replay for me!! I have fixed my code!!

1 solution

 
Share this answer
 
Comments
CyberSecII 18-Oct-20 3:47am    
That answer is not working and its not C#,thank you for taking the time to post a solution!The links posted https://www.codeproject.com/Questions/5269728/Using-VB-NET-to-add-automatically-macro-code-into[^] also not working.Can you post a example code in C# for me to see?

What I want is the code to do this:
Create a doc document and add a custom VBA on it in C# and that just by pressing a button on my form!
Richard MacCutchan 18-Oct-20 3:56am    
Sorry, that was the only reference I could find. But converting VB.NET to C# is quite simple since both languages use very similar syntax, and all the same .NET classes.
CyberSecII 26-Oct-20 10:00am    
I followed the link and created a similar code but what I need now is to save the doc document with my macro in it, how can I do that?
Richard MacCutchan 26-Oct-20 10:06am    
Use the Save or SaveAs method.
CyberSecII 26-Oct-20 10:11am    
look at the What I have tried: section
i did that but the document is saved with no macro in it.
Can you see what i am doing wrong on the code?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900