JackOfPH
asked on
Create a word document using vb 2005
How to create word documents using vb 2005?
Here is what I want to do...
I want to create a new word document, put the contents of a textbox in the word document and save it.
but how can do that?
Please help.
Your assistance is greately appreciated. Thank you!
Jack
Here is what I want to do...
I want to create a new word document, put the contents of a textbox in the word document and save it.
but how can do that?
Please help.
Your assistance is greately appreciated. Thank you!
Jack
'Create Word (late binding)
Dim WordApp As Object
Dim doc As Object
WordApp = CreateObject("Word.Applica tion")
doc = CreateObject("Word.Documen t")
Dim str As String
str = Textbox1.Text
With WordApp.Selection
.Font.Size = WordApp.Selection.Font.Siz e + 2
.Font.Bold = True
.TypeText(str)
End With
Dim fName As String
SaveFileDialog1.Filter = "Documents|*.doc"
SaveFileDialog1.ShowDialog ()
fName = SaveFileDialog1.FileName
If fName <> "" Then
Try
doc.SaveAs(fName)
Catch exc As Exception
MsgBox("Failed to save document" & _
vbCrLf & exc.Message)
End Try
End If
Dim WordApp As Object
Dim doc As Object
WordApp = CreateObject("Word.Applica
doc = CreateObject("Word.Documen
Dim str As String
str = Textbox1.Text
With WordApp.Selection
.Font.Size = WordApp.Selection.Font.Siz
.Font.Bold = True
.TypeText(str)
End With
Dim fName As String
SaveFileDialog1.Filter = "Documents|*.doc"
SaveFileDialog1.ShowDialog
fName = SaveFileDialog1.FileName
If fName <> "" Then
Try
doc.SaveAs(fName)
Catch exc As Exception
MsgBox("Failed to save document" & _
vbCrLf & exc.Message)
End Try
End If
Sorry there was a mistake in the previous code. Here the code I checked right now
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Create Word (late binding)
Dim WordApp As Object
Dim doc As Object
WordApp = CreateObject("Word.Applica tion")
doc = WordApp.Documents.Add
'-- Add text to Document
With WordApp.Selection
.Font.Size = WordApp.Selection.Font.Siz e + 2
.Font.Bold = True
.TypeText("Visual Basic!")
.TypeParagraph()
.Font.Italic = True
.TypeText("This sentence will appear in next paragraph. ")
.TypeParagraph()
End With
'if we need it
WordApp.visible = True
doc.ActiveWindow.Activate( )
Dim fName As String
SaveFileDialog1.Filter = "Documents|*.doc"
SaveFileDialog1.ShowDialog ()
fName = SaveFileDialog1.FileName
If fName <> "" Then
Try
doc.SaveAs(fName)
Catch exc As Exception
MsgBox("Failed to save document" & _
vbCrLf & exc.Message)
End Try
End If
End Sub
End Class
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Create Word (late binding)
Dim WordApp As Object
Dim doc As Object
WordApp = CreateObject("Word.Applica
doc = WordApp.Documents.Add
'-- Add text to Document
With WordApp.Selection
.Font.Size = WordApp.Selection.Font.Siz
.Font.Bold = True
.TypeText("Visual Basic!")
.TypeParagraph()
.Font.Italic = True
.TypeText("This sentence will appear in next paragraph. ")
.TypeParagraph()
End With
'if we need it
WordApp.visible = True
doc.ActiveWindow.Activate(
Dim fName As String
SaveFileDialog1.Filter = "Documents|*.doc"
SaveFileDialog1.ShowDialog
fName = SaveFileDialog1.FileName
If fName <> "" Then
Try
doc.SaveAs(fName)
Catch exc As Exception
MsgBox("Failed to save document" & _
vbCrLf & exc.Message)
End Try
End If
End Sub
End Class
ASKER
Will try all your code...
I will post as soon as I am finished.
I will post as soon as I am finished.
ASKER
Okey, How can I insert a picture in a picturebox to word document that I had created...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
also I found a project in VB6 how to insert picture to word. Play with it
' Purpose
'Open Word and go to a bookmark
'
' Method
'Create a Word.Application server object. Use its Selection.GoTo method to
'the bookmark. Then use Selection.TypeText to enter text.
'
'Note that this project contains a reference to the Microsoft Word 8.0 Object
'Library. You may need to use a different library if you have a different
'version of Word.
Private WordServer As Word.Application
Private Sub Command1_Click()
Dim file_name As String
Dim file_path As String
Dim file_title As String
Dim txt As String
Dim new_txt As String
Dim pos As Integer
Screen.MousePointer = vbHourglass
Command1.Enabled = False
DoEvents
' Open Word.
file_name = txtFilename.Text
file_title = Mid$(file_name, InStrRev(file_name, "\") + 1)
file_path = Left$(file_name, Len(file_name) - Len(file_title))
' Uncomment to show Word.
' WordServer.Visible = True
WordServer.ChangeFileOpenD irectory file_path
WordServer.Documents.Open _
FileName:=file_title, _
ConfirmConversions:=False, _
ReadOnly:=False, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
Revert:=False, _
WritePasswordDocument:="", _
WritePasswordTemplate:="", _
Format:=wdOpenFormatAuto
' Go to the bookmark.
WordServer.Selection.GoTo _
What:=wdGoToBookmark, _
Name:="Disclaimer"
WordServer.Selection.Find. ClearForma tting
With WordServer.Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
' Copy the image to the clipboard.
Clipboard.Clear
Clipboard.SetData Picture1.Picture, vbCFBitmap
' Paste the image into Word.
WordServer.Selection.Paste
' Comment out to keep Word running.
WordServer.Quit True
Set WordServer = Nothing
Screen.MousePointer = vbDefault
Command1.Enabled = True
End Sub
Private Sub Form_Load()
Dim file_name As String
file_name = App.Path
If Left$(file_name, 1) <> "\" Then file_name = file_name & "\"
file_name = file_name & "Readme.doc"
txtFilename.Text = file_name
On Error GoTo OpenError
Set WordServer = New Word.Application
On Error GoTo 0
Exit Sub
OpenError:
MsgBox "Error" & Str$(Error.Number) & _
" opening Word." & vbCrLf & _
Error.Description
End Sub
Private Sub Form_Unload(Cancel As Integer)
' Quit, saving changes.
If Not (WordServer Is Nothing) Then
WordServer.Quit True
Set WordServer = Nothing
End If
End Sub
' Purpose
'Open Word and go to a bookmark
'
' Method
'Create a Word.Application server object. Use its Selection.GoTo method to
'the bookmark. Then use Selection.TypeText to enter text.
'
'Note that this project contains a reference to the Microsoft Word 8.0 Object
'Library. You may need to use a different library if you have a different
'version of Word.
Private WordServer As Word.Application
Private Sub Command1_Click()
Dim file_name As String
Dim file_path As String
Dim file_title As String
Dim txt As String
Dim new_txt As String
Dim pos As Integer
Screen.MousePointer = vbHourglass
Command1.Enabled = False
DoEvents
' Open Word.
file_name = txtFilename.Text
file_title = Mid$(file_name, InStrRev(file_name, "\") + 1)
file_path = Left$(file_name, Len(file_name) - Len(file_title))
' Uncomment to show Word.
' WordServer.Visible = True
WordServer.ChangeFileOpenD
WordServer.Documents.Open _
FileName:=file_title, _
ConfirmConversions:=False,
ReadOnly:=False, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
Revert:=False, _
WritePasswordDocument:="",
WritePasswordTemplate:="",
Format:=wdOpenFormatAuto
' Go to the bookmark.
WordServer.Selection.GoTo _
What:=wdGoToBookmark, _
Name:="Disclaimer"
WordServer.Selection.Find.
With WordServer.Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
' Copy the image to the clipboard.
Clipboard.Clear
Clipboard.SetData Picture1.Picture, vbCFBitmap
' Paste the image into Word.
WordServer.Selection.Paste
' Comment out to keep Word running.
WordServer.Quit True
Set WordServer = Nothing
Screen.MousePointer = vbDefault
Command1.Enabled = True
End Sub
Private Sub Form_Load()
Dim file_name As String
file_name = App.Path
If Left$(file_name, 1) <> "\" Then file_name = file_name & "\"
file_name = file_name & "Readme.doc"
txtFilename.Text = file_name
On Error GoTo OpenError
Set WordServer = New Word.Application
On Error GoTo 0
Exit Sub
OpenError:
MsgBox "Error" & Str$(Error.Number) & _
" opening Word." & vbCrLf & _
Error.Description
End Sub
Private Sub Form_Unload(Cancel As Integer)
' Quit, saving changes.
If Not (WordServer Is Nothing) Then
WordServer.Quit True
Set WordServer = Nothing
End If
End Sub
ASKER
Okey will try it again.
Will post after trying.
Will post after trying.
ASKER
Having an error
The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
Below is my class
Public Class VirusReport
Private WordApps As Word.Application = New Word.Application
Private Missing As Object = System.Reflection.Missing. Value
Private FileName As Object = "Normal.Dot"
Private newTemplate As Object = False
Private DocType As Object = 0
Private isVisible As Object = False
Private WordDoc As Word.Document
Private HeaderFont As New Word.Font
Private NormalFont As Font
Private ShowDocument As Boolean
Private CompName As String = ""
Private UserName As String = ""
Public Overloads Sub FontHeader(ByVal FontName As String, ByVal Size As Integer, Optional ByVal isBold As Boolean = False, Optional ByVal isItalic As Boolean = False, Optional ByVal isUnderline As Word.WdUnderline = Word.WdUnderline.wdUnderli neNone)
HeaderFont.Name = FontName
HeaderFont.Size = Size
HeaderFont.Bold = 1
HeaderFont.Italic = 1
HeaderFont.Underline = isUnderline
End Sub
''' <summary>
''' Set up the normal font for the report
''' </summary>
''' <param name="FontName">The name of the font you want to use. Example: Arial, Times New Roman</param>
''' <param name="Style">The style of the font you use. Example: Bold, Underline, Italic</param>
''' <param name="Size">The Size of the font.</param>
''' <remarks></remarks>
'''
Public WriteOnly Property Show() As Boolean
Set(ByVal value As Boolean)
ShowDocument = value
End Set
End Property
Public WriteOnly Property ComputerName() As String
Set(ByVal value As String)
CompName = value
End Set
End Property
Public WriteOnly Property User() As String
Set(ByVal value As String)
UserName = value
End Set
End Property
Public Sub Initialize()
WordDoc = WordApps.Documents.Add(Fil eName, newTemplate, DocType, isVisible)
WordApps.Visible = ShowDocument
WordDoc.Activate()
WordApps.Selection.Font = HeaderFont ' <----This is where the error was thrown....
WordApps.Selection.TypePar agraph()
WordApps.Selection.Paragra phFormat.A lignment = Word.WdParagraphAlignment. wdAlignPar agraphLeft
WordApps.Selection.TypeTex t(UCase("V irus report" & vbNewLine))
End Sub
End Class
The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
Below is my class
Public Class VirusReport
Private WordApps As Word.Application = New Word.Application
Private Missing As Object = System.Reflection.Missing.
Private FileName As Object = "Normal.Dot"
Private newTemplate As Object = False
Private DocType As Object = 0
Private isVisible As Object = False
Private WordDoc As Word.Document
Private HeaderFont As New Word.Font
Private NormalFont As Font
Private ShowDocument As Boolean
Private CompName As String = ""
Private UserName As String = ""
Public Overloads Sub FontHeader(ByVal FontName As String, ByVal Size As Integer, Optional ByVal isBold As Boolean = False, Optional ByVal isItalic As Boolean = False, Optional ByVal isUnderline As Word.WdUnderline = Word.WdUnderline.wdUnderli
HeaderFont.Name = FontName
HeaderFont.Size = Size
HeaderFont.Bold = 1
HeaderFont.Italic = 1
HeaderFont.Underline = isUnderline
End Sub
''' <summary>
''' Set up the normal font for the report
''' </summary>
''' <param name="FontName">The name of the font you want to use. Example: Arial, Times New Roman</param>
''' <param name="Style">The style of the font you use. Example: Bold, Underline, Italic</param>
''' <param name="Size">The Size of the font.</param>
''' <remarks></remarks>
'''
Public WriteOnly Property Show() As Boolean
Set(ByVal value As Boolean)
ShowDocument = value
End Set
End Property
Public WriteOnly Property ComputerName() As String
Set(ByVal value As String)
CompName = value
End Set
End Property
Public WriteOnly Property User() As String
Set(ByVal value As String)
UserName = value
End Set
End Property
Public Sub Initialize()
WordDoc = WordApps.Documents.Add(Fil
WordApps.Visible = ShowDocument
WordDoc.Activate()
WordApps.Selection.Font = HeaderFont ' <----This is where the error was thrown....
WordApps.Selection.TypePar
WordApps.Selection.Paragra
WordApps.Selection.TypeTex
End Sub
End Class
I see that you are using early binding. Did you add a reference to the Word Object?
ASKER
Yes,
ASKER
Yes, I add the reference
http://www.vbdotnetheaven.com/UploadFile/mgold/WordDocument04182005081441AM/WordDocument.aspx
http://www.c-sharpcorner.com/UploadFile/mgold/WordFromDotNet11082005235506PM/WordFromDotNet.aspx
http://www.vbdotnetheaven.com/UploadFile/sudiptasdas/WordVBXMLXSLT11092006060002AM/WordVBXMLXSLT.aspx