Page 1 of 2 12 LastLast
Results 1 to 40 of 47

Thread: [RESOLVED] Trying to get part of a word document into a variable

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Resolved [RESOLVED] Trying to get part of a word document into a variable

    In VB6 Word Automation, I would like some clue as to how to get *part* of a word document (that happens to include both text and an inserted image) into a variable (for later insertion into another document) using ActiveDocument.Range

    I am trying to use whole story but without success. The part of the document I want to put into the variable starts at the top, has the image and then some text. The part I want to select ends with "BUT"

  2. #2
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Just off the top of my head, I'd consider using the clipboard to get this done. If it's not to be pasted immediately, you could create a "temp" Word document, paste it there, save it, and then copy it back later. (Edit: And I can certainly see my way through how to get this done via VB6 through Automation.)

    I don't have any experience reading binary Byte data from a Word document. I'm not even sure you can do that via Automation.

    If it's a DOCX type file, another option would be to unzip and open the XML document directly. However, that would also be a substantial amount of work.

    This is an example of the complexities of the clipboard. You can rather trivially copy mixed-and-nested formats from Word (or Excel or many other programs) into the clipboard, and then paste them into a compatible document. However, manipulating these mixed-and-nested formats directly (without the original program, i.e., Word) is an entirely different issue.

    Good Luck,
    Elroy
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Quote Originally Posted by Elroy View Post
    Just off the top of my head, I'd consider using the clipboard to get this done. If it's not to be pasted immediately, you could create a "temp" Word document, paste it there, save it, and then copy it back later. (Edit: And I can certainly see my way through how to get this done via VB6 through Automation.)

    Good Luck,
    Elroy
    Thanks for the reply. I'm really new to Word automation. Can you give me some pointers on how you would save to the clipboard (presumably using ActiveDocument?

  4. #4
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Hi el84,

    Okay, the fact that you mentioned the ActiveDocument makes me wonder if you're in the Word VBA, rather than VB6. It's not terribly different either way, but it is a bit different. Here's some quick code on how I'd get a document open for VB6 Automation. Also, note that I always use late-binding:

    Code:
    
        Dim wrd As Object
        Dim doc As Object
    
        Set wrd = CreateObject("Word.Application")
        Set doc = wrd.Documents.Open(sFileSpec)     ' Where sFileSpec is previously specified.
    
    And then, you could use that doc variable to manipulate your document. You could search, move around in the document, select text and objects as you move, etc.

    To move around, you can do things like:

    Code:
    
        doc.ActiveWindow.ActivePane.Selection.MoveRight wdCharacter, 4, wdExtend
        doc.ActiveWindow.ActivePane.Selection.MoveUp wdLine, 1, wdExtend
    ' etcetera.
    
    
    The wdExtend tells it to expand the selection rather than move the carat.

    Once you have your selection, you can do something like:

    Code:
    
        doc.ActiveWindow.ActivePane.Selection.Copy
    
    And then, you've got it in the clipboard. You could then paste it into another Word document.

    But, rather than handing you fish, let me try and teach you to fish a bit.

    When I'm doing stuff like this, I very often use the VBA macro recorder. To put it into VB6 from the VBA, I just replace the ActiveDocument with my doc variable. Sometimes the VBA will use shortcuts (like not fully specifying the Selection object), but those are typically fairly easy patch-ups.

    Maybe that'll get you going.

    Good Luck,
    Elroy

    EDIT1: Also, the Word VBA MSDN (i.e., help system) is also very useful when learning this stuff. To get things done with automation in VB6, I'll often also keep the Word VBA open so I can get help on the various methods I'm using.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  5. #5

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Thank you. I'll try to digest that. 77 year old brain cells...

    This is my code so far, many similarities to yours

    Code:
    Dim docPath As String
    Dim wrdApp As Word.Application
    
    Private Sub Form_Load()
        docPath = "C:\Users\Alan\Documents\"
        Set wrdApp = CreateObject("word.application") 'now wrdApp 'holds' the automation?
    End Sub
    
    Private Sub cmdDoIt_Click()
        Dim Hold As String
        With wrdApp
            .Documents.Open (docPath & "aaTest" & "/aTestIn.docx")
            .Visible = True
            'Hold = .ActiveDocument.Range.WholeStory this line failing and commented out
            'Clipboard commented out for now
            MsgBox ("Look at Word on tray")
            
            .Quit ' this closes Word (at last!)
        End With
    
        MsgBox ("We did it!")
        Set wrdApp = Nothing
        Unload Me
    End Sub

  6. #6
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Ok, a couple of things. You need to create another variable to hold your document once you open it. You're opening it, but you're throwing away your object variable. I'm talking about your line ...

    Code:
    
    .Documents.Open (docPath & "aaTest" & "/aTestIn.docx")
    
    Compare that to my line...

    Code:
    
    Set doc = wrd.Documents.Open(sFileSpec)
    
    Maybe even modified to look something like...

    Code:
    
    Set doc = wrdApp.Documents.Open(docPath & "aaTest" & "/aTestIn.docx")
    
    Then, you've got that "doc" variable that you can do things with.

    Using that, you might do something like the following...

    Code:
    
        doc.ActiveWindow.ActivePane.Selection.WholeStory
        doc.ActiveWindow.ActivePane.Selection.Copy
    
    And then, assuming you get a second (possibly new) document open using similar methods (maybe in a variable named "doc2"), you could paste your text into it as...

    Code:
    
        doc2.ActiveWindow.ActivePane.Selection.Paste
    
    Then, you could just save this second document using the .Save or .SaveAs method.

    I hope that helps a bit.

    Also, that line you commented out ...

    Code:
    
    Hold = .ActiveDocument.Range.WholeStory
    
    A Word document (especially one with pictures and possibly other things) is far from a simple string. In fact, it's pretty much always some kind of object. You can't even come close to just treating them like strings.

    Good Luck,
    Elroy

    EDIT1: By the way, those "doc" and "doc2" variables can be declared "As Document". Or, in my case, with late-binding, I just declare them "As Object". In your case, either will work. But using "As Object", you will lose the Intellisense help, which is nice.
    Last edited by Elroy; Jan 9th, 2018 at 10:20 PM.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  7. #7
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    Quote Originally Posted by Elroy View Post
    A Word document (especially one with pictures and possibly other things) is far from a simple string. In fact, it's pretty much always some kind of object. You can't even come close to just treating them like strings.
    As far as I could tell by reading through the documentation that isn't strictly true.

    This seems to work fine, assuming that's all that was needed:

    Code:
    Option Explicit
    '
    'Serialize a Word.Range to WordML.
    '
    'Requires MS Word 11 (2003) or later.
    '
    
    Private Sub Form_Load()
        Caption = "Working..."
        Timer1.Enabled = True
    End Sub
    
    Private Sub Form_Resize()
        If WindowState <> vbMinimized Then
            Text1.Move 0, 0, ScaleWidth, ScaleHeight
        End If
    End Sub
    
    Private Sub Timer1_Timer()
        Dim Range As Object
    
        Timer1.Enabled = False
        Text1.Visible = False
        With CreateObject("Word.Application")
            .Documents.Open App.Path & "\Sample.doc", ReadOnly:=True
            Set Range = .ActiveDocument.Range(0, 0)
            Range.Find.Execute "BUT", MatchCase:=True, MatchWholeWord:=True, Forward:=True
            Text1.Text = .ActiveDocument.Range(0, Range.End).XML
            Set Range = Nothing
            .Documents.Close
            .Quit
        End With
        Text1.Visible = True
        'We'll just do this the hard way for demo purposes:
        Text1.SelStart = InStr(1, Text1.Text, "BUT", vbBinaryCompare) - 1
        Text1.SelLength = 3
        Caption = "Complete!"
    End Sub
    Name:  sshot.png
Views: 951
Size:  8.0 KB

    Pictures seem to serialize just fine, if bulky.

    Sample .doc included. Only tested in Word 2003!
    Attached Files Attached Files

  8. #8

  9. #9
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    Yes, good point of course. I have Office 2013 on another PC but since I hardly ever use Microsoft's Office anymore I never bothered with more than one copy.

    Even so, I still get Office 2003 updates.

  10. #10
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Ahhh, good point, Dilettante. I've never used any of the XML methods. I suppose, if you're willing to convert to some ASCII/ANSI standard, you can get about anything into a string. There's possibly an RTF option as well, but I haven't explored that.

    I'm still a bit confused about what el84 is going to do with it once he gets it into a string. As I haven't explored those options, maybe you can paste/insert it back in as XML or RTF.

    EDIT1: Also, I wouldn't be at all surprised if the XML option was available only for Word 2007 or later, as that's when the DOCX format got introduced.

    EDIT2: Wait, I just more closely read your (Dilettante's) post. I guess it's available on Word 2003, as that's what he said he used. That's actually quite interesting. Microsoft must have been planning for XML even before the DOCX format was introduced.
    Last edited by Elroy; Jan 10th, 2018 at 10:32 AM.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  11. #11
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    Well Word.Range objects have an InsertXML method so "pasting" it in w/o the clipboard looks possible.

    I also left some references in the Project that I posted above: both "Microsoft Word 11.0 Object Library" and "tom" that I was playing with while fighting Word's grotesque object model. Both of those can be deleted since they aren't being used.

  12. #12
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    I just stumbled upon this:

    History of office XML formats (1998-2006)

  13. #13
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Interesting. I didn't know that Microsoft started embracing XML that far back.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  14. #14
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    Well: Building XML Parsers for Microsoft's IE4

    Microsoft cofounded the XML working group at the W3C in July 96 and actively participated in the definition of the standard. This article describes why Microsoft implemented its first XML application and how it led to the development of two XML parsers shipping in Internet Explorer 4.0, one written in C++ and the other in Java. We describe the importance of designing an object model API and our vision of XML as a universal, open data format for the Internet.

  15. #15
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Well, I was thinking more in terms of Microsoft embracing XML with Office, but that's also interesting. As proprietary as Microsoft has often been, I find it interesting (and, actually, a bit hopeful) that they're embracing these open and publicly maintained standards.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  16. #16

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Thanks all for your input. Most of it is completely above my head. But post #6 is nearer to my understanding level. I will work on that, and possibly report back. One thing though, in that post is said '...you could paste your text into it...'. Just a reminder that it is text *and an image* (ie the (part) contents) which I want to paste.
    Last edited by el84; Jan 10th, 2018 at 03:05 PM.

  17. #17
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    What will work probably depends on what you meant by:

    Quote Originally Posted by el84 View Post
    ... (for later insertion into another document)...
    For an object there is no "later." If you need to store it you need to serialize it.

  18. #18
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Hi el84,

    The way I outlined it in post #6, you will "copy into the clipboard" whatever you selected in the Word document (text, pictures, tables, etc, or any combination). And then, when you paste, you'll paste whatever you put into the clipboard into your new document. I probably should have said "clipboard info" rather than "text".

    Elroy
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  19. #19

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Thanks again. Now I'm really confused because some of the time Intellisense is not offering any drop down list which I assume means I am not entering valid code, for example that line from post #6

    Set doc = wrdApp.Documents...

    I am also unsure whether this all fits into my existing With wrdApp...End With structure

  20. #20
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Hi el84,

    If you have a syntax error in some other part of your code, Intellisense sort of turns off until you fix that. From what I've seen, Intellisense will only work if all but your currently code-line is syntactically correct.

    Good Luck,
    Elroy

    EDIT1: If I were struggling as you seem to be, I'd forget any "With ... End With" blocks until I got things up and running. Then, once it was working, I'd possibly go back and put them in. From an execution perspective (disregarding speed and object reference concerns), With...End With blocks aren't absolutely needed at all.
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  21. #21

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    I understand, but I am comfortable with the way the 'With...End With' structure works, and how it does save repetitive code and keystrokes (always a source of error). I expressed myself badly. I meant how does copy and paste fit into my code generally. In any answer, don't assume I known anything about where things go! I will continue to experiment. Looks like copy and paste is what I need, if I can just find how it all fits together or whether I should discard my code and start afresh. Oh, and thanks for the info re why Intellisense does not seem to be working sometimes!

  22. #22
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Trying to get part of a word document into a variable

    I meant how does copy and paste fit into my code generally
    this thread is pretty much the same as previously asked here http://www.vbforums.com/showthread.p...nto-a-variable
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  23. #23

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Yes, that was me too. I ran out of understanding/steam then. I'll continue with this one. Making substantial progress and will post shortly.

  24. #24

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    OK. Got copy and paste going fairly well, and it does what I want (text and image).

    Code:
    Dim wrdApp As Word.Application
    
    Private Sub Form_Load()
        docPath = "C:\Users\Alan\Documents\"
        Set wrdApp = CreateObject("word.application")
    End Sub
    
    Private Sub cmdDoIt_Click()
            Set inDoc = wrdApp.Documents.Open(docPath & "aaTest" & "\aTestIn.docx")
            inDoc.ActiveWindow.ActivePane.Selection.WholeStory
            inDoc.ActiveWindow.ActivePane.Selection.Copy
            wrdApp.Documents.Close
                    
            Set outDoc = wrdApp.Documents.Open(docPath & "aaTest" & "\aTestOut.docx")
            outDoc.ActiveWindow.ActivePane.Selection.Paste
            wrdApp.Documents.Close '### Word asks 'Would you like to keep...'
                    
            wrdApp.Quit
      
        MsgBox ("Now to Set object variables to nothing")
        Set wrdApp = Nothing
        Set inDoc = Nothing
        Set outDoc = Nothing
        Unload Me
    End Sub
    To get rid of the Word message 'Would you like to keep the last time you copied', I suspect I would need to use something like

    ActiveWindow.ActivePane.Selection.Clear

    after I have pasted.

    I would normally rely on Intellisense to show me the available options. However it is not invoked, which I suspect is something to do with Early v Late Binding, one of the many VB6 things I am extremely hazy about. I would appreciate someone indicating how I might change the code to ensure that I can use Intellisense, ie presumably by getting early binding? I'll then try to puzzle out how to avoid that Word message.

  25. #25

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Updating post above. I have now experimented and found that the last line in this extract apparently does the trick

    Code:
    Set outDoc = wrdApp.Documents.Open(docPath & "aaTest" & "\aTestOut.docx")
            outDoc.ActiveWindow.ActivePane.Selection.Paste
           
            wrdApp.Quit (SaveChanges)

  26. #26

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Spoke too soon. Document now not copying and pasting. Back to drawing board!

  27. #27

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Now using

    ActiveDocument.Save
    wrdApp.Quit(SaveChanges)

    Seems OK...

  28. #28
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Trying to get part of a word document into a variable

    Code:
    wrdApp.Quit true  'save changes
    or use the Word constant


    how to avoid that Word message.
    try
    Code:
    wrdapp.displayalerts = false
    make sure to turn back on at some later point in the code

    outDoc.ActiveWindow.ActivePane.Selection.Paste
    without having tested, i reckon would be the same as
    Code:
    outDoc.Paste
    However it is not invoked, which I suspect is something to do with Early v Late Binding
    while you are using createobject, for your instance of Word, which is the method for late binding, your variable is word.application, so you are actually using early binding,

    you have a value assigned to the docpath variable in form open, but from what is posted above, it is not valid in the procedure where you are using it
    wrdApp.Documents.Close
    while this works, it will close all open documents, better in most cases to specify, the user may have some other documents open, even though they would most likely be in a different instance of word
    Code:
    indoc.close false
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  29. #29

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Thanks Westconn1. As I reported I did manage to solve the problem, but I'll try those too. Or are you saying some of my posted code is superfluous?

    My next problem is that I want to first delete a portion of outDoc (which happens to include a JPG and some text) up to a certain word. And then paste inDoc in place of it. I am sure the command is simple if I know what was doing! Something like

    outDoc.delete.upto = "whatever"

    or

    outDoc.Delete.Range(start, "whatever")

    and then the paste code as already. I don't need to select a portion of inDoc because that will be the right length to substitute in outDoc up to the "whatever".
    Last edited by el84; Jan 12th, 2018 at 10:46 PM.

  30. #30
    Frenzied Member
    Join Date
    Dec 2008
    Location
    Melbourne Australia
    Posts
    1,487

    Re: Trying to get part of a word document into a variable

    Quote Originally Posted by el84 View Post
    I would normally rely on Intellisense to show me the available options. However it is not invoked, which I suspect is something to do with Early v Late Binding, one of the many VB6 things I am extremely hazy about. I would appreciate someone indicating how I might change the code to ensure that I can use Intellisense, ie presumably by getting early binding? I'll then try to puzzle out how to avoid that Word message.
    The "Hitch Hiker's Guide to Office Automation" is available on this site.
    Whenever I feel the need to look it up, it is sometimes a wee challenge for me to find it.
    I think these are the two best links -
    http://www.vbforums.com/showthread.p...App-using-VB-6
    http://www.vbforums.com/showthread.p...using-together
    HTH,
    Rob
    PS I told you it was hard to find
    Here goes another one -
    http://www.vbforums.com/showthread.p...6-(or-VB5-VBA)
    PPS Some of those are for excel, but I am sure that the info on Early vs Late binding will still be helpful
    Last edited by Bobbles; Jan 13th, 2018 at 01:24 AM.

  31. #31
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Hi el84,

    I think you are using the Word Macro Recorder to help you figure some of this out. And that's a good thing. However, there's always a bit of "patching up" to do if you copy that VBA code into VB6. For one, you've always got to replace that "ActiveDocument" statement with one of your declared "doc" variables. Also, the Macro Recorder has a bad habit of not fully specifying the "Selection" object when its using it, and VB6 isn't going to understand that, so that's got to be patched up (i.e., fully specified) as well.

    Regarding early-vs-late binding, I think you understand this, but I'll give you the short version. You always have late-binding when you declare an object variable with "As Object". There are other ways as well, such as "As Form", "As Control", "As IUnknown", and others. But "As Object" is probably the most frequent way you get late-binding. In other words, you have late-binding anytime the specific object's class name isn't used for the declaration.

    And, when you use that specific object's class name, then you have early-binding. There are some speed and performance differences, and there are advantages and disadvantages to each, but that's a larger discussion.

    More to your point, anytime you use late-binding, you lose all of your Intellisense help for that object. If you correctly specify its members (methods & properties), it will still work just fine. You just don't get the IDE help during development.

    Hope that helps.

    All The Best,
    Elroy
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  32. #32
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    I'm still not sure what you are frogging around with. I gave you the answer above in post #7 but you discarded that for this wumpus hunt.

    Here I have two Word documents. SampleSource.doc has a block of content with an embedded picture marked by START and END. SampleToUpdate.doc has an insertion point marker of HERE.

    Code:
    Option Explicit
    
    Private Sub Main()
        Const wdStory = 6
        Const wdDoNotSaveChanges = 0
        Dim Range As Object
        Dim RangeStart As Long
        Dim WordML As String
    
        With CreateObject("Word.Application")
            .Documents.Open App.Path & "\SampleSource.doc", ReadOnly:=True
            Set Range = .Documents.Item(1).Range(0, 0)
            Range.Find.Execute "START", MatchCase:=True, MatchWholeWord:=True, Forward:=True
            RangeStart = Range.Start
            Range.MoveEnd wdStory, 1
            Range.Find.Execute "END", MatchCase:=True, MatchWholeWord:=True, Forward:=True
            WordML = .Documents.Item(1).Range(RangeStart, Range.End).XML
            .Documents.Item(1).Close wdDoNotSaveChanges
    
            .Documents.Open App.Path & "\SampleToUpdate.doc", ReadOnly:=False
            Set Range = .Documents.Item(1).Range(0, 0)
            Range.Find.Execute "HERE", MatchCase:=True, MatchWholeWord:=True, Forward:=True
            Range.InsertXML WordML
            Set Range = Nothing
            .Documents.Item(1).SaveAs App.Path & "\Updated.doc"
            .Documents.Close
            .Quit
        End With
        MsgBox "Complete!"
    End Sub
    Result:

    Name:  sshot.png
Views: 815
Size:  37.3 KB

    Seems to work just fine for me.
    Attached Files Attached Files

  33. #33

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Quote Originally Posted by Elroy View Post
    Hi el84,


    Regarding early-vs-late binding, I think you understand this, but I'll give you the short version. You always have late-binding when you declare an object variable with "As Object". There are other ways as well, such as "As Form", "As Control", "As IUnknown", and others. But "As Object" is probably the most frequent way you get late-binding. In other words, you have late-binding anytime the specific object's class name isn't used for the declaration.

    And, when you use that specific object's class name, then you have early-binding. There are some speed and performance differences, and there are advantages and disadvantages to each, but that's a larger discussion.

    More to your point, anytime you use late-binding, you lose all of your Intellisense help for that object. If you correctly specify its members (methods & properties), it will still work just fine. You just don't get the IDE help during development.

    Hope that helps.

    All The Best,
    Elroy
    Thanks for trying. I don't know anything about class names. In this code, which works fine, have I made a declaration (I think you must mean a Dim) that sets up early or late declaration (or both?) ('Dim WrdApp As Word.Application' ) and what should I specifically change to ensure early binding? And is there a command for delete all before?

    Code:
    Dim wrdApp As Word.Application
    
    Private Sub Form_Load()
        docPath = "C:\Users\Alan\Documents\"
        Set wrdApp = CreateObject("word.application")
    End Sub
    
    Private Sub cmdDoIt_Click()
        
            Set inDoc = wrdApp.Documents.Open(docPath & "aaTest" & "\aTestIn.docx")
            inDoc.ActiveWindow.ActivePane.Selection.WholeStory
            inDoc.ActiveWindow.ActivePane.Selection.Copy
            wrdApp.Documents.Close
                    
            Set outDoc = wrdApp.Documents.Open(docPath & "aaTest" & "\aTestOut.docx")
            'ActiveDocument.Range.Select
            
            outDoc.ActiveWindow.ActivePane.Selection.Paste '### this also works, adding to the top
             
            ' as a separate part, this works well in replacing one word, but I would like to replace
            'a large block (including a jpg) up to a certain word and then paste in.
            'start of separate code
            With ActiveDocument.Range.Find
                .MatchWildcards = True
                .Text = "BUT"
                .Replacement.Text = "NOW"
                .Execute Replace:=wdReplaceOne
            End With   '###This bit is OK
            'end of separate code
    
            ActiveDocument.Save
            
            wrdApp.Quit (SaveChanges) 'this suppresses Word dialogue but line above needed too
            
            Set wrdApp = Nothing
            Set inDoc = Nothing
            Set outDoc = Nothing
            Unload Me
    End Sub
    Anything in there that is redundant?

  34. #34
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Hi el84,

    Yes, sorry. By "declare" I mean Dim (or Public, or Static, or Global, or Friend).

    And yes, a "Class" name is what you use to declare an object variable. VB6 can create its own classes, but it often uses pre-existing ones, especially when doing early-bound automation. You can have a whole hierarchy of classes, which you do when using Word's class/object model.

    For instance, "Application" is a class, "Document" is a class, "Documents" is a collection class, etc etc.

    If you declare (i.e., Dim, etc) explicitly using these class names, you're doing early-binding. If you declare using "As Object", you're doing late-binding.

    I don't actually see your declarations. Are you using "Option Explicit"? If not, I'd VERY HIGHLY recommend that you do. You'll accidentally do all kinds of late-binding if you don't, as all your implicit declarations will be "As Variant", which is even more general than "As Object".

    Also, here's a little example of what I think you're trying to do. You'll definitely need to patch up your document names. And also, you'll need to create that test1.docx document as your source document.

    I just put those Sleep statements in it to slow it down a bit so you could see what it's doing. Also, I used early-binding so, if/when you modify it, you'll have Intellisense.

    I hope that helps.

    Elroy

    Code:
    
    Option Explicit
    Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
    
    Private Sub Form_Click()
        Dim wrd As Word.Application
        Dim doc1 As Word.Document
        Dim doc2 As Word.Document
        Dim doctext1 As Word.Selection
        Dim doctext2 As Word.Selection
    
        Set wrd = New Word.Application
        wrd.Visible = True                          ' So we can see what we're doing.
        Sleep 1000
    
        Set doc1 = wrd.Documents.Open("c:\users\elroy\desktop\test1.docx")
        Set doctext1 = doc1.ActiveWindow.ActivePane.Selection
        Sleep 1000
    
    
        doctext1.HomeKey wdStory, wdMove             ' Make sure we're at the top of the document.
        doctext1.MoveDown wdLine, 4, wdExtend        ' Select four lines, whatever that may be.
        doctext1.Copy                                ' Put our selection in the clipboard.
        Sleep 1000
    
    
        Set doc2 = wrd.Documents.Add                ' A new document.
        Set doctext2 = doc2.ActiveWindow.ActivePane.Selection
        Sleep 1000
    
    
        doctext2.Paste                              ' Paste whaever is in the clipboard into doc2.
        Sleep 1000
    
        doc2.SaveAs "c:\users\elroy\desktop\test1.docx"
        doc1.Close
        doc2.Close
    
        wrd.Quit
    
        ' All procedure level object variables will auto-destroy when the procedure terminates.
    
    End Sub
    
    
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  35. #35

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Looking at this, and also the code shown by Dilettante (many thanks to both), I am reminded that there are several ways of achieving the same end in vb6 (or I suppose any programming environment).

    I should refine my previous request more carefully (excuse the tunnel thinking. It's a medical thing -- literally)! I have managed, using copy and paste as suggested by Elroy, to copy one document including a JPG into another.

    What I need to do to complete the original requirement, is first of all delete part of the second document (which includes both a jpg and some text) and after that, paste in the new one (happens to be a complete document). I am trying to find a delete method which specifies the range from the document start up to a particular word.

    Meanwhile, yes I usually do place Option Explicit. Don't know why I left that out. Also I understand about the New. Odd thing now is that if I place Option explicit, then wrdApp.Quit(SaveChanges) which previously allowed me to finish without leaving anything open, now tells me that SaveChanges is a variable not defined!

    I am much more able to function if I import either of the suggestions kindly shown by either of you into my own code.

  36. #36
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: Trying to get part of a word document into a variable

    I was pretty sure you said you wanted to grab some text-with-picture from one document and then insert it into other documents later. This WordML String value can be stored in a file, etc. for later use, while Clipboard contents can be more problematic to serialize. Not to mention that you trash the user's Clipboard contents in the process, something always to be avoided where practical.

  37. #37
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    el84,

    I've got no idea what these documents look like, but it sounds like a search-and-possibly-replace problem. You can you search (actually "Find") to help with your selection as well. Here are a couple of functions I often use:

    Code:
    
    Option Explicit
    Const wdStory = 6
    Const wdMove = 0
    Const wdFindContinue = 1
    
    Public Sub InWordGotoTopOfDocument(doc As Object)
        Dim DocText As Object
        '
        Set DocText = doc.ActiveWindow.ActivePane.Selection
        DocText.HomeKey wdStory, wdMove
    End Sub
    
    Public Function InWordFindStringInBody(doc As Object, sText As String) As Boolean
        ' Always starts at the top.  There is no notice if it's not found.
        Dim DocText As Object
        '
        InWordGotoTopOfDocument doc
        Set DocText = doc.ActiveWindow.ActivePane.Selection
        '
        DocText.HomeKey wdStory, wdMove             ' Move insertion point to top of document.
        DocText.Find.ClearFormatting                ' Make sure we're not searching for fonts, bold, etc.
        DocText.Find.ClearFormatting
        DocText.Find.Text = sText
        DocText.Find.Replacement.Text = vbNullString
        DocText.Find.Forward = True
        DocText.Find.Wrap = wdFindContinue
        DocText.Find.Format = False
        DocText.Find.MatchCase = False
        DocText.Find.MatchWholeWord = False
        DocText.Find.MatchWildcards = False
        DocText.Find.MatchSoundsLike = False
        DocText.Find.MatchAllWordForms = False
        InWordFindStringInBody = DocText.Find.Execute ' Returns True if the find operation is successful. Boolean.
    End Function
    
    Now again, I use late-binding for all of this. With your early-binding, you won't need to declare those constants at the top.

    Also, you may not want it to go to the top before searching. Or you may need to modify them in other ways to suit your needs.

    Here are some more snippets that may help you:

    Code:
    
    Option Explicit
    Const wdStory = 6
    Const wdMove = 0
    Const wdFindContinue = 1
    Const wdReplaceAll = 2
    Const wdReplaceOne = 1
    
    Public Sub InWordReplaceFirstOccurenceInBody(doc As Object, OldText As String, Optional NewText As String, Optional NewTextColor As Long = -1)
        ' ********
        '    Note: Word truncates these inserts at 255 characters.  See ....Ex versions.
        ' ********
        '
        ' If the NewText field is not supplied, the old field is blanked out.
        ' This one can't deal with shapes.
        Dim DocText As Object
        '
        InWordGotoTopOfDocument doc
        Set DocText = doc.ActiveWindow.ActivePane.Selection
        DocText.HomeKey wdStory, wdMove             ' Move insertion point to top of document.
        InWordDoTheReplace DocText, OldText, NewText, True, NewTextColor
    End Sub
    
    Public Sub InWordGotoTopOfDocument(doc As Object)
        Dim DocText As Object
        '
        Set DocText = doc.ActiveWindow.ActivePane.Selection
        DocText.HomeKey wdStory, wdMove
    End Sub
    
    Public Sub InWordDoTheReplace(DocText As Object, OldText As String, Optional NewText As String, Optional OnlyOne As Boolean, Optional NewTextColor As Long = -1, _
                                  Optional bMatchWholeWords As Boolean, Optional bMatchCase As Boolean)
        ' Searches from the current position forward.
        On Error Resume Next ' The search and replace may not work on all shape types.
            DocText.Find.ClearFormatting                ' Make sure we're not searching for fonts, bold, etc.
            DocText.Find.Replacement.ClearFormatting    ' Make sure we're not searching for fonts, bold, etc.
            '
            DocText.Find.Text = OldText
            DocText.Find.Replacement.Text = Left$(NewText, 255)
            '
            DocText.Find.Forward = True
            DocText.Find.Wrap = wdFindContinue
            DocText.Find.Format = False
            DocText.Find.MatchCase = bMatchCase
            DocText.Find.MatchWholeWord = bMatchWholeWords
            DocText.Find.MatchWildcards = False
            DocText.Find.MatchSoundsLike = False
            DocText.Find.MatchAllWordForms = False
            If OnlyOne Then
                DocText.Find.Execute Replace:=wdReplaceOne
            Else
                DocText.Find.Execute Replace:=wdReplaceAll
            End If
            ' And now we can optionally set the color of the text we just pasted.
            If NewTextColor <> -1 Then DocText.Font.Color = NewTextColor
        On Error GoTo 0
    End Sub
    
    Enjoy,
    Elroy
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  38. #38

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    Thanks again. See the last 2 paras of post #35. I have real problems moving away completely from what I've already written. Also what about that odd effect of Quit(SaveChanges). Why does the program demand that I dimension SaveChanges? I imagined that was just an argument of Quit? If I leave out Option Explicit it all works OK but if I put in Option Explicit it demands! What do I dimension it to? Object?

  39. #39
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    9,852

    Re: Trying to get part of a word document into a variable

    Application.Quit Method (Word)

    Word Enumerated Constants (WdSaveOptions) <--- be sure to scroll down to WdSaveOptions. There, you'll find the allowed constants which will already be declared for you, and should be shown by Intellisense.

    Maybe that'll help.

    Good Luck,
    Elroy
    Any software I post in these forums written by me is provided "AS IS" without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. To all, peace and happiness.

  40. #40

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2012
    Location
    Australia
    Posts
    1,162

    Re: Trying to get part of a word document into a variable

    OK That's fixed the save changes thing! I now have

    Option Explicit on again

    and then I use

    wrdApp.Quit SaveChanges:=wdSaveChanges

    as suggested
    which incidentally seems to mean I no longer need

    ActiveDocument.Save
    wrdApp.Documents.Close

    before that line

    My original aim was to take one document which had a jpg followed by some text, and replace that jpg and text with another jpg and text which makes up the whole of another document. I am finding experimentally that if I define a range that ends in the text, and delete that range, then the jpg before it is deleted too, on these lines

    Set myRange = ActiveDocument.Range(0, 2)
    myRange.Delete

    Nearly time to post the much modified code for any comments from those who are not already bored to tears!

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width