PDA

View Full Version : Reading Variables in Word



Dohko8
08-27-2007, 04:09 AM
Hi

I'm new to writing macros in word and was wondering if the following is possible.

Suppose I have the following

Name: James State: Florida

How can I write a macro that will read and store James in variable x. and Florida in variable y?

Thanks

lucas
08-27-2007, 05:59 AM
simple example with a userform with one textbox:
Private Sub UserForm_Initialize()
Dim x As String
x = "James"
TextBox1.Value = x
End Sub

Dohko8
08-27-2007, 06:02 AM
But say I have a word document with this data and the Name:
will be the same but the James will change. Is there anyway to tell Word to store anything after Name:, in this case James but to stop before State?

I'm focusing on the selection.find property but cant get it to work/

Thanks

lucas
08-27-2007, 06:15 AM
http://www.vbaexpress.com/forum/showthread.php?t=11427

Dohko8
08-27-2007, 06:21 AM
Thanks, I'll check it out

Dohko8
08-27-2007, 07:39 AM
So i need to create a bookmark for this? Can't get it to work
Any other ideas?

fumei
08-27-2007, 09:45 AM
Can't get it to workThis means absolutely nothing. Zip.

Can't get WHAT to work?

Using a bookmark?
The code?

And if doesn't work...what DOES happen??

I'm new to writing macros in word and was wondering if the following is possible.

Suppose I have the following

Name: James State: FloridaWhile the others made an assumption that a userform is involved...I don't know that. Is a userform involved?

WHERE is "Name: James State: Florida"?????

Are the chunks ( James, Florida) in a table? Perhaps different cells? If they were, this would be MUCH easier.

WHAT, exactly, are you using in your .Find? "James"?

BTW: you probably do NOT have to use Selection.Find. In fact, due to the way the object model handles a Range.Find, you would most likely be much better using Range.
Sub testJames()
Dim r As Range
Dim var1 As String
Dim var2 As String
Dim count As Long
Set r = ActiveDocument.Range
With r.Find
.ClearFormatting
.Text = "James"
Do While (.Execute(Forward:=True) = True) = True
' above sets r temporarily to a .Found "James"
var1 = r.Text ' so var1 = "James"
r.Expand Unit:=wdSentence
count = r.Words.count
' this gets the last word
var2 = r.Words(count - 1)
MsgBox var1 & vbTab & var2
' displays "James Florida"
r.Collapse Direction:=wdCollapseEnd
' you MUST collapse r
Loop ' goes to next "James"
End With
End Sub

Caveats!!!!

Using wdSentence will work if you are correctly using Styles! If you are using those "extra" paragraphs - using the Enter key to make spaces - it will NOT work. It would have to be adjusted.

The key point is that the variable r itself changes as it goes through the .Find. It was the whole document, but it is dynamically resized for each .Execute = True.

Therefore you can use each .Found as a distinct value.

How, exactly, you can grab the end word (Florida) depends entirely on where this text is.

Again, is it in a table?

If not, does the line terminate in a paragraph mark?

Dohko8
08-27-2007, 10:36 AM
It is not a table.
It doesn't have any specific formatting. It's just a Word document with some information.
I want to be able to record whatever goes after Name: and State:
The line that contains the State field just ends with a Enter.
It's like this

Name: James State: Florida City: Tallahassee

No specific formatting, just want to be able to capture the names. Is it possible to just search for Name and record everything that's no the field between (in this case James) and State?


Hope this makes things more clear

fumei
08-27-2007, 11:02 AM
Sigh.....

Who said anything about special formatting?

You never mentioned there was anything after State. Now there is City. This makes a difference. You can hardly use the last word of the paragraph if what you want is NOT the last word. My code above was based on what YOU posted, where "Florida" was the last word.

Now, also, you use the word "field". Sigh. Is it really a field? Or are you just using that word because you want to? Because if it IS some sort of field, then this is another ball game altogether.

record everything that's no the field between (in this case James) and State?
I don't understand this. First of all, I assume that "no" is actually "not".

Everything that is not between James and State.

Hmmm. There is nothing between James and State, so I have no idea what you are talking about.

The bottom line is this. If it is text in a Word document, you can, with proper specifications, get anything you want. And yes, you can get it into a variable.

Good luck.

Dohko8
08-27-2007, 11:06 AM
This is just an example.
I just want to know how to store some text into a variable.


Selection.Find.ClearFormatting
With Selection.Find
.Text = "Name:"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
myRangeStart = Selection.End
Selection.Find.ClearFormatting
With Selection.Find
.Text = "State:"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
myRangeEnd = Selection.Start
Set rngSelect = ActiveDocument.Range( _
Start:=myRangeStart, _
End:=myRangeEnd)
rngSelect.Select
v1a = rngSelect

This code works but only works for the first variable, I don't know how to make it work with more than one.

fumei
08-27-2007, 12:09 PM
As you are not answering questions, NOR taking any suggestions I will leave it up to others to help.

I just want to know how to store some text into a variable.Easy...assign the text to the variable. Like this:

variable = text (as string)

There. Your question is answered.

How can I get this through to you? You say: "I just want to know how to store some text into a variable."

No...you don't. Because if that WAS what you "just want to know", here is the answer again.

You assign the text to the variable. Period. Full stop. That IS how you " store some text into a variable."

But that is not your question, now is it? When you finally get around to actually asking what you really want to know, maybe someone will help you.

I've tried. BTW: in your code above...there ARE no variables, so I have no idea what you mean by "first variable".

As for finding, I have clearly (I think) explained why it is better, and more useful, to use a Range. But are you even commenting on that? No. Are you even asking any questions about it? No. Are you answering direct questions asked of you? No.

Using Selection.Find as you are, you will never get what I think you want to happen. No, not quite true. You could get it, but it would be messy, and very inefficient.

I have posted code that got "Florida" with a search using "James" out of:

Name: James State: Florida

Did you even try it?

I have amended it to get "Florida" with a search for "James" out of:

Name: James State: Florida City: Tallahassee

with both "James" and "Florida" being assigned to variables.

It can be done, and actually with not all that much difficulty. All it takes is clear statements, and maybe answering direct questions when they are asked of you.

I will repeat myself. The bottom line is this. If it is text in a Word document, you can, with proper specifications, get anything you want. And yes, you can get it into a variable.

I think I am done here.

Dohko8
08-28-2007, 07:32 AM
Hi

I'm new to VBA and have a question.

I have a word document that has the following information

Name: John State: FL

I want to be able to read John and FL and store it in variables x1 and x2.
John and FL can change, Name and state will always be the same.
This information is not in a table or styles. Just plain text.

Thanks

fumei
08-28-2007, 09:45 AM
Excuse me????

You need to read up on how to use these forums.

You have posted this exact same question in another thread. What? You did not like the answers so you think you can just ask again?

Please do not repeat threads.

If you want an answer follow through on what you have already started.

I will be glad to help if you act properly. That means answering questions.

I have told you already, this can be done.

In your first thread you stated the data was "Florida". Now it is "FL"? What, you think this does not make a difference? I have told you - be clear, be specific....and answer questions. It would also help if you actually posted a document so we can see it.

In the example above you no longer have City: Miami (or whatever)

Does the text have a City after....or not? What, do you not think that would make a difference?

I have told you - be clear, be specific, be EXACT....and answer questions.

Again...DO NOT repeat threads. Finish the one you started.

Dohko8
08-28-2007, 09:57 AM
I'm trying to be more specific. James and Florida will change.
Name: State:
will always be the same
In the code above, it looks for James, I can't do that because it won't be james all the time. The way I was thinking is how to select a range after Name: and before State, store that variable as x1, and whatever is after State store that as x2.

fumei
08-28-2007, 10:34 AM
Try this. If the document does not look like yours, try posting up a sample so we can actually SEE what you are doing.

Look, I am trying to help, but if you want to play in this sandbox you have to play by some rules.

lucas
08-28-2007, 10:43 AM
Threads merged. Gerry is absolutly right. With a little patience and cooperation you can get your questions answered and more.

lucas
08-28-2007, 10:52 AM
As Gerry points out this can be done and it can be done in several ways. The first of this thread pointed you to a different thread where bookmarks were used to put data in the sheet and retrieve them. You should read it and if you have questions...ask them here. That thread employs a userform for data input to add to the sheet. Then you are able to retrieve that same data...

The biggest problem here..and Gerry also pointed this out is that we don't really know what you're trying to accomplish. It would help immensly if you could post your document and tell us exactly what you want to do.

Dohko8
08-28-2007, 10:55 AM
I'll try to be more specific now. That i posted my sample file.

Select the text that occurs between "Name:" and "Number:" (in this example James )
Save this to a variable named "v1"
Select the text that occurs between "Number:" and "APPENDIX A:"
(in this example 00000123654)
Save this to a variable named "v2"
Select the text that occurs between "APPENDIX A:" and "APPENDIX B:"
(means the whole paragraph)
Save this to a variable named "v3"
Select the text that occurs between "APPENDIX C:" and the end of the file
Save this to a variable named "v4"

Reason I need this is so I can create a new document using this information programatically.

Hope this is more clear.

Thanks

fumei
08-28-2007, 12:17 PM
Finally. Finally you are actually saying something.

If you want to use Word this way you must learn Word.

The sample doc has bookmarks for the first two actions

Select the text that occurs between "Name:" and "Number:" (in this example James )
Save this to a variable named "v1"
Select the text that occurs between "Number:" and "APPENDIX A:"
(in this example 00000123654)

Using bookmarks is absolutely the best way to go. And if you could use bookmarks it would make what you want to do VERY EASY. You simply assign the bookmark text to a variable.

For example:Dim x1 As String
x1 = ActiveDocument.Bookmarks("name").Range.TextVoila! x1 = "James "

Note the extra spaces. The bookmark HAS those extra spaces. Of course you get rid of them.Dim x1 As String
x1 = Trim(ActiveDocument.Bookmarks("name") _
.Range.Text)

Voila! x1 = "James"

However, I suspect you do not know how to use bookmarks. I further suspect that the real document you will be working with will not even have any bookmarks. So that leaves working with just text.

What you want to do is a matter of logic. Which means, perhaps unfortunately, that one has to be logical.

To go back to my comment about knowing Word, AND going back to a question asked - which was never answered:
Select the text that occurs between "APPENDIX A:" and "APPENDIX B:"
(means the whole paragraph)The question was how these chunks of text are terminated.

You think (it seems) that the text between "APPENDIX A:" and "APPENDIX B:" is one paragraph. "whole paragraph"

Sorry...but it is not. That chunk of text is SIX separate and distinct paragraphs. Each line is terminated by a paragraph mark. It is SIX paragraphs.

This is precisely why I have been asking questions.

This fact - that it is six paragraphs, NOT one - makes a huge difference in how you need to get the text you want.

Now IF these were bookmarked, again it would be VERY EASY to get the text you want. A snap.

As it is, with the lines terminated by paragraphs marks, it is very difficult. Not impossible, but a lot more work.

However, again, and I can not stress this enough, it is purely a matter of logic. And your criteria does not have any. From Word's perspective, these are random searches for text.

Let me see if I can put it better. In your post above there are four actions. Here they are, A, B, C, D.

A
1. Find "Name".
In terms of logic, there must be NO other "Name". Otherwise there must be logic statements to know which one to use.
2. Put the next word into variable v1

B
1. Find "Number"
In terms of logic, there must be NO other "Number". Otherwise there must be logic statements to know which one to use.
2. set a marker at the end of "Number"
3. Find "APPENDIX A:"
4. set a marker at the start of "APPENDIX A:"
5. set a marker at the end of "APPENDIX A:" - to be used for action C below
5. assign the text between the first two markers to variable v2

C
1. find "APPENDIX B:"
2. set a marker for the start of "APPENDIX B:"
3. assign the text between the marker after "APPENDIX A:", and the marker before "APPENDIX B:" to variable v3

D
1. find "APPENDIX C:"
2. set a marker at the end of "APPENDIX C:"
3. assign the text from this marker to end of doc to v4

THAT is the logic.

Now....is there ANY similar, reuseable logic between/within those four actions???

No, there is not.

Therefore, each of those actions is completely and utterly separate and distinct. What that means is you have to code each one distinctly. Each action has to be its own procedure because there is no common logic.

If they are bookmarked...its a snap. Here. I changed your document and bookmarked the text you want. I put the macro as a menubar item - "TryIt!". Click that.

You will get a inputbox asking you to enter a bookmark name. i used your examples: v1, v2, v3, v4.

Type in one of those (without the comma!) and press Enter. Or click OK....whatever.

A message box will display the input variable.

Reason I need this is so I can create a new document using this information programatically.If you are going to be doing that, you had better get an deeper understanding of how Word works.

If you can bookmark your source text chunks you will be 80% of the way to getting your chunks into a new document.

No offense, but I shudder to think about how you are going about making this new document programmatically.

Bottom line. As the demo doc attached shows, it is EASY to get text out of bookmarks and put it into variables.

If the text is NOT bookmarked, then you will have to do one step at a time searching and resetting of ranges and markers and yadda yadda yadda.

There you have it.

fumei
08-28-2007, 12:32 PM
Actually, ummmmm, in the my demo doc above I did not bother to actually put the contents into variables, as logically it was not needed. So here is the code to technically put the text into actual variables.Sub tryIt()
Dim v1 As String
Dim v2 As String
Dim v3 As String
Dim v4 As String
v1 = ActiveDocument.Bookmarks("v1").Range.Text
v2 = ActiveDocument.Bookmarks("v2").Range.Text
v3 = ActiveDocument.Bookmarks("v3").Range.Text
v4 = ActiveDocument.Bookmarks("v4").Range.Text

Dim response As String
response = InputBox("Please enter one of the bookmarks. " _
& vbCrLf & vbCrLf & "Valid choices are: v1, v2, v3, v4" _
& vbCrLf & vbCrLf & "Do NOT use the comma!")
Select Case response
Case "v1"
MsgBox "v1 variable contains:" & _
vbCrLf & vbCrLf & v1
Case "v2"
MsgBox "v2 variable contains:" & _
vbCrLf & vbCrLf & v2
Case "v3"
MsgBox "v3 variable contains:" & _
vbCrLf & vbCrLf & v3
Case "v4"
MsgBox "v4 variable contains:" & _
vbCrLf & vbCrLf & v4
Case Else
MsgBox "You typed something wrong. 'Bye."
End Select
End SubThe reason my demo doc seemed to show a variable (but did not really) is that often a variable is NOT needed. In the above case, the logic required did NOT require the use of a variable...so why use one?

My demo used:Case "v1"
MsgBox "v1 variable contains:" & _
vbCrLf & vbCrLf & ActiveDocument.Bookmarks("v1").Range.Text
Case "v2"
MsgBox "v2 variable contains:" & _
vbCrLf & vbCrLf & ActiveDocument.Bookmarks("v2").Range.Text
' etc etc.There was no need - from a logic POV - to declare, or use, a variable. I retrieved the text directly.

In terms of getting content and creating a new document, it is often the same thing. People declare and use variables when there is no need at all.

Dohko8
08-29-2007, 06:39 AM
Thanks.

The bookmark solution works well, problem is that the document I'll be using will not have bookmarks.

So what you're saying is that If I don't add bookmarks I have to store each line in a variable and do one by one.
Is there a way to select the whole paragraph from one document and just paste it into another new document?

The Excel Macro recorder lets me copy information from cells from one sheet to another but the Word one won't let me select the text and copy it to a new document. Any way of doing this?

Thanks for your patience.

fumei
08-29-2007, 01:26 PM
So what you're saying is that I have to store each line in a variable and do one by one.
No, that is not what I am saying at all.

I am saying you have to use individual, separate, pieces of logic to get the chunks you want.

You use the word "paragraph", but it is clear to me you do not know what "paragraph" means, to Word. Here is the text from your sample document. You state you want to get everything from APPENDIX A: to APPENDIX B:


APPENDIX B: Random Paragraph
Water busts the backspace against its whale.
A fever pinches the rag.
Water privileges a blanket. Can our baffle sweep?
Water projects the paradox opposite the glove.

APPENDIX B:

I will repeat what I have already stated. This is NOT one paragraph.

APPENDIX B: Random Paragraph = 1 paragraph
Water busts the backspace against its whale. = 1 paragraph
A fever pinches the rag. = 1 paragraph
Water privileges a blanket. Can our baffle sweep? = 1 paragraph
Water projects the paradox opposite the glove. = 1 paragraph
= 1 paragraph (the space here IS a paragraph)
APPENDIX B:

If those lines were one paragraph (and in a proper document it would be!), then grabbing the text of it would be easy.


Is there a way to select the whole paragraph from one document and just paste it into another new document?See above. Which is the paragraph? There are SIX of them.

Is there a way to copy paragraphs to a new document? Yes, sure. It is easy.ActiveDocument.Paragraphs(4).Range.Copy
Documents.Add
ActiveDocument.Range.PasteThere. The fourth paragraph of the active document is copied; a new document created; that paragraph is pasted into the new document.

There. Your question is answered.
Is there a way to select the whole paragraph from one document and just paste it into another new document?Is there a way? Yes, and it is easy and simple to do.

Your problem is that your document does not have proper paragraphs. It is easy to copy paragraphs, but you have to point Word to the paragraph, now don't you? WHICH paragraph do you want to copy. Word will do it when you tell it which one.

Now if you are specifically asking: "how do I copy the current selection to another document?"

This is a manual operation, so try using the Copy and Paste buttons. That is what they are for.

So there is another answer to your question.
Is there a way to select the whole paragraph from one document and just paste it into another new document?

Yes, use the Copy and Paste buttons and switch between the documents.

But - as usual - you are probably not stating what you really want. I am guessing that you want to do this by code, some sort of automation process.

So, I will repeat myself again - and this is becoming tedious. It is a matter of logic. If you write the logic, and hand it to Word, then Word will do it. It is a piece of software. Generally, it does what it is told to do. YOU have to tell it the correct things to do.

Can you take the text as you have it (with all those lines terminated by paragraphs marks) and get anything you want out of it?

The answer is an unqualified YES, you can. I even wrote out the logic for each action in a previous post. And, for my own interest, I wrote the code to actually do it. Am I going to post it for you?

No, I am not.

If you really want code to do this, try doing it yourself. When you get stuck - and you will - ask real questions. Specific questions. If you try, and ask real questions, I will help you. But I am not going to just hand over a solution to you.

And for your own sake, try and do some research on Word itself. You will never code well in Word until you understand "paragraph". It is completely essential.