This project has moved. For the latest updates, please go here.
' create vba macros and run in Word
' taken from Example05.vb
Private Sub Example05Main()

   ' start word and turn off msg boxes
   Dim wordApplication As New Word.Application
   wordApplication.DisplayAlerts = WdAlertLevel.wdAlertsNone

   ' add a new document
   Dim newDocument As Word.Document
   newDocument = wordApplication.Documents.Add()

   ' add new module and insert macro
   ' the option "Trust access to Visual Basic Project" must be set
   Dim newModule As NetOffice.VBIDEApi.CodeModule
   newModule = _
newDocument.VBProject.VBComponents.Add( _
vbext_ComponentType.vbext_ct_StdModule).CodeModule ' set the modulename newModule.Name = "NetOfficeTestModule" ' add the macro Dim codeLines As String codeLines = String.Format("Sub NetOfficeTestMacro()" & Environment.NewLine & _
" {0}" & Environment.NewLine & _ "End Sub", _
"Selection.TypeText (""This text is written by a automatic created macro"")") newModule.InsertLines(1, codeLines) 'start the macro wordApplication.Run("NetOfficeTestModule!NetOfficeTestMacro") 'save the document Dim fileExtension As String = GetDefaultExtension(wordApplication) Dim documentFile As String = _
String.Format("{0}\Example05{1}", Application.StartupPath, fileExtension) newDocument.SaveAs(documentFile) ' close word and dispose reference wordApplication.Quit() wordApplication.Dispose() Dim fDialog As New FinishDialog("Document saved.", documentFile) fDialog.ShowDialog(Me) End Sub #Region "Helper" ''' <summary> ''' returns the valid file extension for the instance. for example ".doc" or ".docx" ''' </summary> ''' <param name="application">the instance</param> ''' <returns>the extension</returns> ''' <remarks></remarks> Private Function GetDefaultExtension(ByVal application As Word.Application) As String Dim version As Double =
Convert.ToDouble(application.Version, CultureInfo.InvariantCulture)
If (version >= 12.0) Then Return ".docx" Else Return ".doc" End If
End Function #End Region

Last edited Jun 13, 2012 at 8:55 AM by SebastianDotNet, version 6


No comments yet.