Solved

Word to VB question

Posted on 2000-04-26
36
609 Views
Last Modified: 2010-08-05
I have some code

Private Sub Command1_Click()
    On Error GoTo errWordNotOpen
    Dim appWord As Word.Application
    Dim docWord As Word.Document
    Dim rngWord As Word.Range
    Set appWord = GetObject(, "Word.Application")
    If appWord Is Nothing Then
        Set appWord = CreateObject("Word.Application")
    End If
    appWord.Visible = True
    Set docWord = appWord.Documents.Open(Dir1.Path & "\" & File1.FileName)
    ' Code for finding fields etc.,
    Set rngWord = docWord.GoTo(What:=wdPage, Which:=wdGoToAbsolute, Count:=1)
   
    With rngWord.Find
      .Execute "School", True, True
       
       
       rngWord.EndOf Unit:=wdParagraph, Extend:=wdExtend
       
    End With
   
    docWord.Close
    Set docWord = Nothing
    appWord.Quit
    Set appWord = Nothing
Exit Sub

via a PAQ, and I need to find certain fields and then save them to a database.  I understand the database part, but I can not find the syntax or resource to search the document.  I can find what I need manually, but how do I get the very next field?  The same applies for tables.  Can someone give me an example, like on page 1 Search for Thunder and need the data after it, like it would be search for Thunder and pring out Chicken if that were the next text after it.  I looked all around MSN and EE, but came up empty.  It will open the document, which I'd prefer if it left it closed so people can see the progress on the VB application.

Thanks.
0
Comment
Question by:thunderchicken
  • 14
  • 14
  • 3
  • +4
36 Comments
 
LVL 5

Expert Comment

by:CreateObject
Comment Utility
So what you need is a way to read a string of
text and search it for certain words, then extract
data after those words?

Sounds a bit troubling... you ask, how can I get
to the very next field?  What kind of field, a text
field on the Word Doc, or a database field?

0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
There is basically a user that has already created a Word Document that about 110 other users have used to input information.  The document is roughly 60 pages long.  There are some pages with tables, some with just text.  I guess I can manually program to look at that exact spot, but I'll need to get the information after, since it will vary.  The program will pop open a file box so the user can find the document (which is done) then when they click on the "start" button, which is the code above, it will search the document, display the progress in a label, and overall in a progress bar, then submit it to a MS-SQL database (which there is boocoo information on doing that).  I know it's a lot of coding to do all that, which there is no real loop to do it, since the key words to find the information will vary, so all I'm asking for are two examples from the code I have.

1. Find the text after a keyword to another keyword (since the length will vary)
2. Find information in a table

Thanks
0
 
LVL 6

Expert Comment

by:Marine
Comment Utility
Post a link to this question in MsOffice there are people who will be able to help you.
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
Buy http://www.experts-exchange.com/jsp/qShow.jsp?ta=msoffice&qid=10310894

There are several solutions there, my favorite is

Here is a slightly more compact version:

Sub PrintPagesWithCodeword()
  'Prints all pages with a given string
   
  'Declare variables
  Dim Message As String
  Dim Title As String
  Dim Default As String
  Dim SpecialCode As String
  Dim LastPrintedPage As Long
   
  'Read SpecialCode from user
  Message = "Only pages containing following text (case sensitive) will be printed: " ' Set prompt
  Title = "PrintPagesWithCodeword"
  Default = "XYZ"   ' Set default, is set as case sensitive below.
  SpecialCode = InputBox(Message, Title, Default)
   
  'Move selection to beginning of document
  Selection.HomeKey Unit:=wdStory
   
  'Set parameters for Find
  With Selection.Find
    .Format = False
    .Forward = True
    .Wrap = wdFindStop
    .MatchCase = True
    .MatchAllWordForms = False
    .MatchFuzzy = False
    .MatchSoundsLike = False
    .MatchWholeWord = True
    .MatchWildcards = False
  End With
   
  'Keep finding while the text is found
  Do While Selection.Find.Execute(FindText:=SpecialCode)
    'If this page hasn't been printed
    If Selection.Information(wdActiveEndPageNumber) <> LastPrintedPage Then
      'Print current page
      Application.PrintOut Range:=wdPrintCurrentPage
      'Remember the last printed page number
      LastPrintedPage = Selection.Information(wdActiveEndPageNumber)
    End If
  Loop

End Sub
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
I bought the question and printed it out, but from what I am looking at, isn't this code just finding certain text and printing out what page it is on?  What I want is to find the text and display what is directly after it.

- Thunderchicken
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
I understood your question that your main problem was to find the string. I should have stated that you would have to adapt the code. Sorry.

As for your question: What do you mean with "...display what is directly after it " ? Select it ? Copy and return it in a messagebox ?


 


0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
Well, the things I would be searching for would be key words, and the text right after it would vary, thus the information I needed.  I would just put it in a variable and upload it to a database.  I will also at that time display it in a label just for the user's convience.

- Thunderchicken
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
This is work in progress, take with a grain of salt....


ub ReturnWordRight2Codeword_v1()
  ' Returns all words just to the right to a given string
 
  ' Room for improvement:
  ' - Does not work in tables, unless codeword and word in same cell
  ' - Reading of selection perhaps far too complicated
     
  ' Declare variables
  Dim Message As String
  Dim Title As String
  Dim Default As String
  Dim SpecialCode As String
  Dim MyData As DataObject
  Dim RetWord As String
 
  ' Read SpecialCode from user
  Message = "Codeword (case sensitive) is: " ' Set prompt
  Title = "ReturnWordRight2Codeword_v1"
  Default = "XYZ"   ' Set default, is set as case sensitive below.
  SpecialCode = InputBox(Message, Title, Default)
   
  'Move selection to beginning of document
  Selection.HomeKey Unit:=wdStory
   
  'Set parameters for Find
  With Selection.Find
    .Format = False
    .Forward = True
    .Wrap = wdFindStop
    .MatchCase = True
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWholeWord = True
    .MatchWildcards = False
  End With
   
  Do While Selection.Find.Execute(FindText:=SpecialCode)
    ' to 'get out' of codeword
    Selection.MoveRight Unit:=wdWord, Count:=1
    ' Select next word
    Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend
    ' Copy word to clipboard
    Selection.Copy
    ' Move on
    Selection.MoveRight Unit:=wdWord, Count:=1
    ' From help, do not understand why needed...
    Set MyData = New DataObject
    MyData.GetFromClipboard
    ' Fetch word
    RetWord = MyData.GetText(1)
    ' For testing only
    MsgBox (RetWord)
   
  Loop

End Sub
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
Oops...

Sub ReturnWordRight2Codeword_v1()  
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
So the syntax for this would be, for example if I wanted to find what was next to the word, "Fred" I'd say

ReturnWordRight2Codeword_v1("Fred")

so what about multiple pages?  I'll know exactly where it is on the page, just not whats after it.

Thanks
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
Right now it is writen as Sub (with user interaction). It should work accross multiple pages. Please test the searching functionality, then I can change it to a function.

In order to simplify it: How many times does the same codeword appear in the document ?



0
 
LVL 13

Expert Comment

by:cri
Comment Utility
Regarding tables: Do you have any rules, especially whether codeword is the last word (including trailing spaces) in a given cell ?
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
Adjusted points from 100 to 150
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
The codeword will appear more than once, but with a consistant document, i can get the first one, or as many as i want, and still have a consistant order all documents are in.

Codeword last word --  Doubtful, the table will be the easy part.  I'll know exactly where at on the page to goto, and therefore, wont need any keywords.  As long as I say, "hey, the data i need for this field in the database is at A5", or whatever, "then I'll throw it in the database in this field".

thanks
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
Ok, waiting for your manual testing.

And, sorry, I still have only a very foggy idea what this actually will be good for, perhaps a much better solution can be devised.
0
 
LVL 2

Expert Comment

by:hhamster
Comment Utility
If you know how to do this manually, then use one example, start macro saving, do it manually, stop the macro and then analyze, modify and insert it into your code.
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
I'll start work on it tomorrow, since all these pages are different, which is why i have to do this manually, because the database fields are the same and each individual user will be using this program to convert this.  I'll let you know tomorrow.

Thanks for all your help
0
 

Expert Comment

by:scibberme
Comment Utility
For the first part of your question, do you basically mean that you want to find a piece of text in a word document(outside of any tables or special containers) and then find the word after it?
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 22

Accepted Solution

by:
ture earned 150 total points
Comment Utility
thunderchicken,

Here is my contribution. It finds the next word (or the first word in the next cell if the keyword is found in a table).

Sub FindNextWord(WordToFind As String)
  Dim NextWord As String
 
  'Move selection to beginning of document
  Selection.HomeKey Unit:=wdStory
   
  'Set parameters for Find
  With Selection.Find
    .Format = False
    .Forward = True
    .Wrap = wdFindStop
    .MatchCase = True
    .MatchAllWordForms = False
    .MatchFuzzy = False
    .MatchSoundsLike = False
    .MatchWholeWord = True
    .MatchWildcards = False
  End With
   
  'Keep finding while the text is found
  Do While Selection.Find.Execute(FindText:=WordToFind)
    Do
      'Move selection to beginning of next word or cell
      If Selection.Tables.Count = 0 Then
        Selection.MoveRight Unit:=wdWord
      Else
        Selection.MoveRight Unit:=wdCell
      End If
      'Select entire word and get it's text
      Selection.Expand Unit:=wdWord
      NextWord = Selection.Text
    Loop Until Asc(NextWord) > 32
   
    'Show the found word
    MsgBox NextWord
   
    'Shrink selection to a cursor only
    Selection.End = Selection.Start
  Loop
End Sub

Sub TestIt()
  FindNextWord "Company:"
End Sub

Ture Magnusson
Karlstad, Sweden
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
ture, starvEEd ?

a) .MatchFuzzy = False 'only Word 2000 and unnecessary in my opinion.

b) MsgBox (Nextword) ?

c) I think thunderchicken needs a function which will return Nextword to a calling sub.

PS: If you look at my 'clipboarding': Would I qualify to work at Microsoft ? I mean, as programmer ?
0
 
LVL 22

Expert Comment

by:ture
Comment Utility
cri,

Yes. I am StarvEEd!

Thanks for the MatxhFuzzy pointer. I wasn't aware that it is a new feature in Word 2000.

MsgBox was only used to show which words are actually found. I don't really know what thunderchicken wants to do with the found results. He has it in a variable (NextWord) and can use it as he prefers.

No, Cri. If I had only seen this post, I might have recommended you for the MS Programming position. However, I have seen many other of your other posts, and know that you often fail to comply with the stipulated Cut'n'Paste methodology. :o)

/Ture
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
ture, I think I got misunderstood in two accounts.

a) Did not know that you can use MsgBox w/o the parenthesis

b) Cut'n'Paste methodology ? I did not mean that I started with the print macro you made for my question for ACS, I mean how I assigned Nextword to the variable.
0
 
LVL 22

Expert Comment

by:ture
Comment Utility
Cri,

Yes, I misunderstood you. But I think I got you right this time...

a) We all learn something new every day at EE...

b) It's good to know how to get the contents of the clipboard. I know I have used this in the past, but forgot how it was done.
However, in this case I think it is a bit overkill. Unless I am missing something, it seems easier to simply use RetWord = Selection.Text.

/Ture
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
..it seems easier...you bet. My problem is that OOP more often than becomes Oops...  
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
I made an encryption program and forgot to save it as Form2, thus I saved it as Form1, which overwrote the Word->VB Program we're working on.  :)

Before I restart on this again, is there anything I should do, possibly approach this is a different way?  I took one VB class in college, so I am quite unfamiliar with the many different things I can do.  I'm a C++ guy, but write in VB script lately so I figured VB would be the answer.

Thanks
0
 

Expert Comment

by:scibberme
Comment Utility
If all you want to do is search through the text in a word document, you could open it using a richtextbox (takes just one method call) and then search through its text property. I really have no idea about the table thing, though.
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
I have to take into consideration both the text and the table.  All the user will see is just a "Run Me" button and it will just show a progress bar, then they can go back and play solitare like most users do during 8am to 5pm.  I was going to display the progress in a label and a progress bar for the rare office workers that don't play solitare (and maybe minesweeper is broken).
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
cri, i just implemented your function, and i got a

Compile error:
Invalid use of New keyword

error in line

Set MyData = New DataObject

---------------------------------------

Ture's seemed to work, just need to play around with it a little bit, I'll keep you informed...

I'll be more than happy to distribute extra points for more helpful information.

0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
aaak.. okay i read the remainder of the post... so the code ture gave me will only work with word 2000 documents?  I am pretty sure this was written in Office 97, but I am working with NT 5.0, word 2000 and VB 6.0.  What happened exactly with ture's code is that it kept looping within a table and kept adding roman numberals (from a pre-existing table), then I had to manually shut down the program.  Initially it worked, but I'll also have to test it on other platforms.  So still in limbo, but working my best on it.  :)
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
thunderchicken, forget my code, especially the DataObject which is as necessary as gout.

Go for ture, he runs circles around me regarding VBA.

My reference regarding Office 2000 is only the a.m. '.MatchFuzzy = False' delete it or inactivate by preceding it with a '

As for the table. If I _read_ it right, ture's code assumes that the code word will be alone in the cell. Is this correct ? If yes: Is there a chance that a trailing space is included ?

 
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
Actually from playing around with his code, it's working fine (so far, ofcourse i've have to adapt it to the document).

Actually with the table, that is fine too, I am just getting started on this and i'll have to code in all the keywords into the code.  I'm just basically taking it one by one.

He's in an opposite time zone right now so I'm just seeing what I can do.
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
If you have a 'flat fee' internet access _and_ low telephone costs:
http://msdn.microsoft.com/library/officedev/office97/web/fulltoc.htm
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
flat fee internet?
i take it that you mispasted...


anyway, thank link helped me out.
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
No, as far as I know an internet access which is not charged per hour but per month/year is called this way. I have pasted it here as you mentioned that you are new into VBA.

Additionally: As VBA help is not in the standard Office setup, re-run Setup, it is handy too.
0
 
LVL 11

Author Comment

by:thunderchicken
Comment Utility
I just love it, you work for days on stuff like this, then your boss tells you they don't need it.  Aaargh, welcome to the programming world!  Code worked, had to adapt a little bit and didn't get my hands deep into it, thanks ture and cri for your help!
0
 
LVL 13

Expert Comment

by:cri
Comment Utility
You are welcome.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now