[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3280
  • Last Modified:

How to create a new Word Document using VB Code?

Hello Experts,

I am developing an Visual Baisc application. This application creates word documents by taking the content from the user.

Here is the specification........

A VB form contains below text fileds......

Book Title:                  _____________
Chapter Number:         _____________
Chapter Title:             _____________
Chapter Text:             _____________
Notes:                        _____________
   
User will enter content in above text files and press Submit Button.  Then i need to create a word document with above content. And this document will be saved in Desktop of the user system.

When i searched on the internet for the code. I found below of the sample vb code.  But it doesn't have my requirement.

===============
           Dim oApp As New Word.Application
           Dim oDoc As New Word.Document

            Set oApp = CreateObject("Word.Application")
            Set oDoc = oApp.Documents.Add
            oApp.Visible = False


            ''' Here i need to insert the above content into the word document.

           
            oDoc.SaveAs (newfpath)
            oDoc.Close
            oApp.Quit
            Set oApp = Nothing
            Set oDoc = Nothing
===============

Could you please provide some sample code for inserting content into the word document?

Thanks in advance,
itsvtk
0
Thandava Vallepalli
Asked:
Thandava Vallepalli
  • 2
  • 2
1 Solution
 
Thandava VallepalliAuthor Commented:


Chapter Text & Notes are text areas and remaining fields are text boxes......

I need to display Chapter Text & Notes in separate paragrahs.


itsvtk
0
 
GrahamSkanCommented:
Not sure what you mean by text areas. I tested it using VB textboxes with the MultiLine property set to True.

Option Explicit

Private Sub Command1_Click()
    Dim oApp As Word.Application
    Dim oDoc As Word.Document
    Const strDocName = "MyBook"
   
    Set oApp = CreateObject("Word.Application")
    oApp.Visible = True 'Show application until this code is stable, else aborts could leave invisible intances of Word running
    Set oDoc = oApp.Documents.Add '(Template)
    oDoc.Range.Text = txtBookTitle.Text & vbCr
    oDoc.Bookmarks("\EndOfDoc").Range.Text = txtChapterNumber.Text & vbCr
    oDoc.Bookmarks("\EndOfDoc").Range.Text = txtChapterTitle.Text & vbCr
    oDoc.Bookmarks("\EndOfDoc").Range.Text = txtChapterText.Text & vbCr
    oDoc.Bookmarks("\EndOfDoc").Range.Text = txtNotes.Text & vbCr
   
    oDoc.SaveAs (GetDeskTopPath & "\DeskTop\" & strDocName)
    oDoc.Close
    oApp.Quit
    Set oApp = Nothing
    Set oDoc = Nothing
End Sub
Function GetDeskTopPath() As String
    Dim strEnviron As String
    Dim strParts() As String
    Dim i As Integer
    i = 1   ' Initialize index to 1.
    Do
        strEnviron = Environ(i)   ' Get environment
        strParts = Split(strEnviron, "=")
        If strParts(0) = "USERPROFILE" Then
            GetDeskTopPath = strParts(1)
            Exit Function
        End If
        i = i + 1   ' Not PATH entry,
    Loop Until strEnviron = ""
End Function
0
 
Thandava VallepalliAuthor Commented:
Thanks GrahamSkan.

Half of my work is over with your solution. But How to apply formatting for the above text.....

Here is the formatting specification...

=================
The top of the word document i.e. first line/heading is Chapter #.  e.g. "Chapter 3". It is centered and Bold.

Then second line will be the Title of chapter 3 for e.g. "World War II".  It is centered and Bold.
We must have one line gap between the Chapter number and the chapter titles.

then.. two lines gap...

and then the Chapter text should begin...

after the entire section is over.. we will add the text 'Notes/Bibliography' as a sub-heading. It is Bold.
below this Sub-heading... whatever text was enter in the text area for Notes/Bibliography must be shown

but in the header.. of the word document first page of Chapter 3 should be the chapter number i.e. "Chapter 3"
and the second page should be the chapter title.. i.e. "World War II"  and they should alternate...

and in the footer we have to add the page numbers
=================

Waiting for your valuable reply,

itsvtk
0
 
GrahamSkanCommented:
Please not that Word has many facilites that you might be bypassing.
For instance you can assign Heading styles to paragraphs that are used as headings or sub-headings. These can be numbered automatically.
Also, you may want to use a Master and Subdocument set-up to keep the chapters editable separately or as a whole.

I wasn't sure what you wanted to do with the Book title, so I assigned the Buil-in property 'Title' to it as well as using it in the file name.
Also, I decided to use some different techniques.

Option Explicit

Private Sub Command1_Click()
    Dim oApp As Word.Application
    Dim oDoc As Word.Document
    Dim Para As Word.Paragraph
    Dim strDocName As String
   
    Set oApp = CreateObject("Word.Application")
    'Set oApp = GetObject(, "Word.Application")
    oApp.Visible = True 'Show application until this code is stable, else aborts could leave invisible intances of Word running
    Set oDoc = oApp.Documents.Add '(Template)
   
    'Book title
    strDocName = txtBookTitle.Text
    oDoc.BuiltInDocumentProperties("Title") = strDocName
    oDoc.Paragraphs.Add oDoc.Bookmarks("\EndOfDoc").Range
   
    'Chapter Number
    Set Para = oDoc.Paragraphs.Last.Previous
    Para.Range.Text = txtChapterNumber.Text
       
    Para.Format.Alignment = wdAlignParagraphCenter
    Para.Format.SpaceAfter = CentimetersToPoints(0.3)
    Para.Range.Font.Bold = True
    Para.Range.Font.Size = 16
    Para.Range.Font.Name = "Arial"
   
  'Chapter Title
    oDoc.Paragraphs.Add oDoc.Bookmarks("\EndOfDoc").Range
    Set Para = oDoc.Paragraphs.Last
    Para.Range.Text = txtChapterTitle.Text
    Para.Format.Alignment = wdAlignParagraphCenter
    Para.Format.SpaceAfter = CentimetersToPoints(0.6)
    Para.Range.Font.Bold = True
    Para.Range.Font.Size = 14
    Para.Range.Font.Name = "Arial"
   
    'Body Text
    oDoc.Paragraphs.Add oDoc.Bookmarks("\EndOfDoc").Range
    Set Para = oDoc.Paragraphs.Last
    Para.Format.Alignment = wdAlignParagraphLeft
    Para.Format.SpaceAfter = 0
    Para.Range.Font.Bold = False
    Para.Range.Font.Size = 12
    Para.Range.Font.Name = "Times New Roman"
    oDoc.Bookmarks("\EndOfDoc").Range.Text = txtChapterText.Text & vbCr
    'Sub Heading
    oDoc.Paragraphs.Add oDoc.Bookmarks("\EndOfDoc").Range
    Para.Format.SpaceBefore = CentimetersToPoints(0.3)
    Para.Range.Font.Bold = True
    Para.Range.Font.Size = 12
    Para.Range.Font.Name = "Arial"
    Para.Range.Text = "Notes/Bibliography"
   
    oDoc.Paragraphs.Add oDoc.Bookmarks("\EndOfDoc").Range
    Set Para = oDoc.Paragraphs.Last
    Para.Range.Font.Bold = False
    Para.Format.SpaceAfter = 0
    Para.Range.Font.Size = 12
    Para.Range.Font.Name = "Times New Roman"

    oDoc.Bookmarks("\EndOfDoc").Range.Text = txtNotes.Text & vbCr
   
    oDoc.SaveAs (GetProfilePath & "\DeskTop\" & strDocName & "_" & txtChapterNumber.Text)
    oDoc.Close False
    oApp.Quit
    Set oApp = Nothing
    Set oDoc = Nothing
End Sub

Function GetProfilePath() As String
    Dim strEnviron As String
    Dim strParts() As String
    Dim i As Integer
    i = 1   ' Initialize index to 1.
    Do
        strEnviron = Environ(i)   ' Get environment
        strParts = Split(strEnviron, "=")
        If strParts(0) = "USERPROFILE" Then
            GetProfilePath = strParts(1)
            Exit Function
        End If
        i = i + 1
    Loop Until strEnviron = ""
End Function

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now