Manipulating content in Microsoft Word with VBScript or VBA

醉酒当歌 提交于 2020-01-03 05:34:06

问题


I've come here for plenty of advice on how to develop VBScript and VBA applications using Excel, but now I've been faced with a new challenge: develop a VBScript/VBA application for Word.

I know, in Excel, if I wanted to type "my name" in cell B3, I would type this:

Range("B3").Value = "my name"

I need to be able to locate where a name and address for a formal letter would be entered, as well as today's date, and my initials as a signature.

I thought I might be able to find VBScript/VBA programming for Word on the internet like I did for Excel, but it seems like working with Word is not as popular. If anyone has any snippets to get me started, or a really good link to a site on the internet where I can do the coding myself, it would be greatly appreciated.

UPDATE

Here is the code I'm working with at the moment:

Public Sub WordVbaDemo()
  Dim doc As Document: Set doc = ActiveDocument ' Or any other document
  DateText = doc.Range(doc.Paragraphs(1).Range.End - 20, doc.Paragraphs(1).Range.End - 18).Text
End Sub`

I need the code to work for a formal letter where the date is right-justified:

                                                               Date: November 7th, 2016

The code I have above will copy the date text after "Date: ". The original template doesn't have a prefilled date. If I enter one, the "Member: " field looks offset like this:

                                                               Date: November 7th, 2016
                                                   Member:

I'm looking for a way to enter text without upsetting the alignment.

UPDATE 2

I forgot to mention this has to work as an external script. This means, if I were to open NotePad and create a script that would fill out a letter in a Word document, that is how it should work. I do apologize for this...got ahead of myself and forgot that detail.

UPDATE 3

I'm using the following code derived from code I use to find any open Internet Explorer windows. I know IE and Word are two different things, but I was hoping I could use Shell to find the Word doc and be able to manipulate the content.

Dim WinDoc, Window, TitleFound
Dim WShell, objShell

Function Check_Document()
    On Error Resume Next
        Set WShell = CreateObject("WScript.Shell")
        Set objShell = CreateObject("Shell.Application")
    On Error GoTo 0

    Window = "non-member template.docx" 'Tried this without the .docx and failed

    TitleFound = False

    For Each WinDoc In objShell.Windows()
        If Err.Number = 0 Then
             If InStr(WinDoc.Document.Title, (Window)) Then
                Set objWord = WinDoc
                TitleFound = True
                Exit For
             End If
          End If
    Next

    If TitleFound = False Then
        MsgBox "Word doc not found"
    Else
        MsgBox "Found Word doc!!"
    End If

End Function

回答1:


I was in a similar boat about 6 months ago. I had done VBA in Excel, but was asked to do some more in Word. The thing about Word VBA is that there are far fewer reasons to need to automate a Word document than an Excel document. From what I've gathered, most situations involve creating legal documents.

I've come a long way and I do have a number of sites bookmarked that I'll dig further into for you.. but this one is a quickstart to using VBA in Word. http://word.mvps.org/faqs/MacrosVBA/VBABasicsIn15Mins.htm

But one pointer: consider if the document layout is going to be structured or not.(It wasn't clear to me in your question). If the layout is going to be structured, where you know exactly where everything is going, you might want to use bookmarks. Otherwise, you may consider the paragraphs method as indicated by z32a7ul.

My project uses UserForms as input. It's been a real challenge at times, but by using Userforms with Bookmarks, I'm able to allow the user to navigate back and forth in the userForms as well as re-run the macro (assuming they have not deleted required bookmarks).

Of course, take this with a grain of salt since I'm still learning as well. For what it's worth, I've also had the added challenge of making this all work on the Mac platform.




回答2:


As a starting point:

Public Sub WordVbaDemo()
    Dim doc As Document: Set doc = ActiveDocument ' Or any other document
    ' doc.Paragraphs(2).Range.Text = "Error if the document is empty (there is no second paragraph)."
    doc.Paragraphs(1).Range.Text = "First paragraph overwritten." & vbCrLf
    doc.Paragraphs(2).Range.Text = "Now I can write to Paragraph 2." & vbCrLf
    doc.Paragraphs.Add(doc.Paragraphs(2).Range).Range.Text = "Inserted between Paragraph 1 and 2." & vbCrLf
    doc.Range(doc.Paragraphs(3).Range.End - 3, doc.Paragraphs(3).Range.End - 2).Font.StrikeThrough = True
    doc.Range(doc.Paragraphs(3).Range.End - 2, doc.Paragraphs(3).Range.End - 2).Text = 3
    doc.Range(doc.Paragraphs(3).Range.End - 3, doc.Paragraphs(3).Range.End - 2).Font.StrikeThrough = False
    With doc.Tables.Add(doc.Range(doc.Range.End - 1), 2, 2)
        .Cell(1, 1).Range.Text = "Header1"
        .Cell(1, 2).Range.Text = "Header2"
        .Cell(2, 1).Range.Text = "Value1"
        .Cell(2, 2).Range.Text = "Value2"
        Dim varBorder As Variant: For Each varBorder In Array(wdBorderTop, wdBorderBottom, wdBorderLeft, wdBorderRight, wdBorderVertical, wdBorderHorizontal)
            .Borders(varBorder).LineStyle = wdLineStyleSingle
        Next varBorder
        .Rows(1).Shading.BackgroundPatternColor = RGB(123, 45, 67)
        .Rows(1).Range.Font.Color = wdColorLime
    End With
End Sub



回答3:


First of all, I want to thank everyone who replied. You helped guide me to my solution. Below is the code I came up with to locate where a name and address for a formal letter would be entered, as well as today's date, and my initials as a signature.

Function Check_Document()
    On Error Resume Next
        Set objWord = CreateObject("Word.Application")
    On Error GoTo 0

    objWord.Visible = True
    Set objDoc = objWord.Documents.Open("C:\Users\lpeder6\Desktop\myDoc.docx")

    Set objRange = objDoc.Bookmarks("TodaysDate").Range
    objRange.Text = "November 11th, 2016"
    Set objRange = objDoc.Bookmarks("Name").Range
    objRange.Text = "John Smith"
    Set objRange = objDoc.Bookmarks("Address").Range
    objRange.Text = "123 N. Anywhere Ave."
    Set objRange = objDoc.Bookmarks("City").Range
    objRange.Text = "Northwoods" & ", "
    Set objRange = objDoc.Bookmarks("State").Range
    objRange.Text = "MN"
    Set objRange = objDoc.Bookmarks("Zip").Range
    objRange.Text = "55555"
    Set objRange = objDoc.Bookmarks("Init").Range
    objRange.Text = "JS"
End Function

The bookmarks are preset within the document so the code has something to look for. Anything within these fields gets replace with the objRange.Text. Variables could be used to store information if this was external coding and the variables would contain data from arguments sending the data.

I hope this code helps others as much as it helped me. Thanks again to everyone who offered me ideas that got me here.



来源:https://stackoverflow.com/questions/40466722/manipulating-content-in-microsoft-word-with-vbscript-or-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!