PDA

View Full Version : Selecting a specific text box only



Duane
08-18-2004, 08:44 AM
Hi there,

I recorded a macro that creates a textbox with "draft" in it to indicate a draft. I recorded another macro that selects a text box and deletes it.

Problem is, it identifies the specific text box, so if another text box is created subsequently, the macro to delete won't work, because it will be looking for "#8" or whatever it is, rather than the one I want.

So, I changed the code to look like this...

Sub DraftClear()
'
' DraftClear Macro
'
ActiveDocument.Shapes.SelectAll
Selection.ShapeRange.Delete
End Sub

SelectAll is groovy, BUT if the document has other text boxes in it, this code will delete them all.

So, I want the code to only select the textbox with "draft" written in it. Assuming this is possible at all, how might I accomplish this?

Thanks, you can probably tell easily that I'm about as new to VBA as can be.
I appreciate any help you can provide.

jamescol
08-18-2004, 09:45 AM
Hi Duane,
Sounds like you need to create your textbox and then assign a name to it first.

1. From the Forms toolbar, insert a TextBox
2. Right-click the TextBox and select Properties to open the Text Form Field Options dialog box
3. In the Bookmark field (towad the bottom of the dialog box) enter a name for your TextBox called Draft.
4. Click OK

These steps assign the TextBox a friendly name you can use in your code to reference it.

Now use the following example to see how to select, retrieve, and modify the textbox's value.

Sub TestBookMark()
Dim txtMyBookmark As String

'Select the Bookmark
ActiveDocument.Bookmarks("Draft").Select

'Set the bookmark's value
ActiveDocument.FormFields("Draft").Result = "Original Value"

'Return the bookmark's current value
txtMyBookmark = Selection.Text
MsgBox txtMyBookmark

'Set the bookmark's value
ActiveDocument.FormFields("Draft").Result = "New Value"

'Return the bookmark's new value
txtMyBookmark = Selection.Text
MsgBox Selection.Text

End Sub


Hope this helps.

James

Duane
08-18-2004, 10:33 AM
James,

Thanks for the prompt reply. Because I'm so unfamiliar with VBA for Word (or, VBA period, for that matter), I may still need some kid gloves.

The code to delete a text box would have to know what that last text box was named.

Picture this -- an admin assistant who knows nothing about VBA opens a document from a partner and stamps it draft; circulates it for revisions, makes those revisions, and then wants to get rid of the draft text box. However, before receiving this document back from the partners, may open any number of subsequent documents, each of which would be stamped draft, and which may return to the admin assist in some other order other than that by which they were received.

So, the delete macro would have to be able to "know" the name of the draft text box in the particlar document it was in at the time (this macro is saved in Normal.doc to be available for any document that is opened at the time).

I'm gathering from your response thus far that, in order for the delete code to do this, the stamp code requires some user input to name the text box, yes?

jamescol
08-18-2004, 12:58 PM
Duane,
We can develop a VBA solution to fit your process. The code doesn't necessarily require any input for creating or deleting the textbox. You will need to clarify a few steps to ensure we tackle the correct issues. I'm pretty sure we can automate everything you need.

Let me recap what I understand, and ask you to confirm/elaborate.

1. An Admin receives a document from a partner.
A) I assume partner in this case indicates a partner in the firm, not an outside vendor sometimes referred to as a partner?

B) The documents received are not necessarily the same standard template; they vary in purpose and format?

2. The Admin needs to mark the document as a draft prior to sending to others for review and revision.

A) Do you have certain requirements for the placement, size, or font of the DRAFT text?

B) You want to have the code in the Admin's normal.dot place the DRAFT text on the document?

C) Does the DRAFT text have to be in a textbox, or can the code place it on the document another way?

3. The Admin send the document for review/revision.

A) Is the document sent via email? If so, would you want to automate sending the document as part of marking it a DRAFT?

B) How are revisions collected/collated? Is the Admin using the Track Changes feature and then merging changes?

4. Once revisions are complete, the Admin needs to run some code to remove the DRAFT text from the document.

A) You want to remove all traces of the DRAFT text and/or field form the document? In other words, no other text should replace DRAFT, it just disappears?

5. The Admin will have several different documents for various partners marked DRAFT at any given time. The documents may not be returned or completed in the order the Admin marks and distributes them, so the code needs to be able to work regardless of the incoming/outgoing order?

A) So the Admin maintains control over when a certain document is ready to have its DRAFT text removed. There are no other criteria other than the Admin's being ready to run the code to remove the text?

James

Duane
08-18-2004, 01:39 PM
James,

Very thorough response, see my [DA] answers below...


Duane,
We can develop a VBA solution to fit your process.

[DA] "Solution development" is overkill for this, I'm just toying with learning VBA from a practical point of view for my own knowledge, so I don't want to waste your time doing more than I can use at this time!

The code doesn't necessarily require any input for creating or deleting the textbox. You will need to clarify a few steps to ensure we tackle the correct issues. I'm pretty sure we can automate everything you need.

Let me recap what I understand, and ask you to confirm/elaborate.

1. An Admin receives a document from a partner.
A) I assume partner in this case indicates a partner in the firm, not an outside vendor sometimes referred to as a partner?

[DA] Correct.

B) The documents received are not necessarily the same standard template; they vary in purpose and format?

[DA] Correct.

2. The Admin needs to mark the document as a draft prior to sending to others for review and revision.

A) Do you have certain requirements for the placement, size, or font of the DRAFT text?

[DA] Something prominent in the upper right corner. For font I use Impact 36 pt in 25% gray, italicized.

B) You want to have the code in the Admin's normal.dot place the DRAFT text on the document?

[DA] Correct.

C) Does the DRAFT text have to be in a textbox, or can the code place it on the document another way?

[DA] The admin assist had started doing this manually with a text box, and I just thought I'd automate her specific task (she didn't ask, just thought I'd surprise her). But, great question. Putting it in the header can be another viable option, as long as removing "DRAFT" does not also remove any other data that may be in the header, depending on the document.

3. The Admin send the document for review/revision.

A) Is the document sent via email? If so, would you want to automate sending the document as part of marking it a DRAFT?

[DA] No, paper-oriented practice.

B) How are revisions collected/collated? Is the Admin using the Track Changes feature and then merging changes?

[DA] No, paper-oriented practice. They do it by hand in pen.
4. Once revisions are complete, the Admin needs to run some code to remove the DRAFT text from the document.

A) You want to remove all traces of the DRAFT text and/or field form the document? In other words, no other text should replace DRAFT, it just disappears?

[DA] Good thought, but it's basically just draft or not.

5. The Admin will have several different documents for various partners marked DRAFT at any given time. The documents may not be returned or completed in the order the Admin marks and distributes them, so the code needs to be able to work regardless of the incoming/outgoing order?

[DA] Correct.

A) So the Admin maintains control over when a certain document is ready to have its DRAFT text removed. There are no other criteria other than the Admin's being ready to run the code to remove the text?

[DA] Correct.

James
So, in a nutshell, my original question was how a macro could recognize a text box as new text boxes are created on a continuing basis. Visioning this routine on the basis of text in the header gets the job done while I learn in my own time how to better manipulate "shapes".

Kelly
08-18-2004, 02:22 PM
Hi everybody!

How about checking inside of each textbox to see if it contains the word "draft" ?

This could be set up in different ways depending on exactly the effect that is desired, for example:


What if the textbox says "Draft #1" or "This is a draft" ?


Should the search (for the word "draft") be case sensitive? ("DRAFT" "Draft" "draft" - dealt with as the same or different?)
Anyway, for starters, how about just deleting any textbox that CONTAINS "draft" (not case sensitive)...

an example:

Sub RemoveBoxIfItSaysDRAFT()

Dim aShape As Shape

For Each aShape In ActiveDocument.Shapes

If aShape.Type = msoTextBox Then

If InStr(1, aShape.AlternativeText, "draft", vbTextCompare) > 0 Then aShape.Delete

End If

Next

End Sub

I'm attaching a sample document.

In my sample document, there are FOUR text boxes. Two contain the word draft, and the other two don't. Only the boxes containing "draft" will be deleted.

You could add many more text boxes to the document, with and without "draft" to play around with and test out the macro.

-Kelly
kellyjones.netfirms.com (http://kellyjones.netfirms.com/visualbasic/vbawelcome.html)

Kelly
08-18-2004, 02:28 PM
Oh my gosh!

I just realized that James and I are talking about 2 different kinds of "text boxes."

James is talking about the kind you can insert using the Forms toolbar, and I am talking about the "Text Box" you can insert using the Drawing toolbar OR BY going to "Edit" (on the regular old menu bar at the top of the Word screen) then "Text Box."

Perhaps Duane can verify, but I think Duane is using the "drawing" type of textbox because Duane's macro mentions:
ActiveDocument.Shapes

hmmm....

Duane
08-18-2004, 03:33 PM
... but I think Duane is using the "drawing" type of textbox because Duane's macro mentions:
ActiveDocument.Shapes

hmmm....
Kelly, you're right on, and the script you provided seems to address my inquiry fairly appropriately.

jamescol
08-18-2004, 03:40 PM
Duane,
My thought was to use a watermark rather than a TextBox, especially since you print out your documents for review and revisions. This way you have a single macro to insert a very visible yet transparent "DRAFT" text on each page of the document.

The RemoveWaterMark macro will, obviously, remove the watermark from the document. Because the code sets the Watermark name to a known entity during the InsertWaterMark macro, the remove macro can delete it easily no matter what order the documents arrive.

I know this is a departure from the Textbox idea, but a watermark is more traditional and it simple to include on all document pages.

BTW - I tested this code on Word 2003 and Word XP. If you are using an earlier version, it's possible you may run into an error. If so, post the error and we can fix it.

Let me know your thoughts.

James



Sub InsertWaterMark()
Dim strWMName As String

On Error Goto ErrHandler

ActiveDocument.Sections(1).Range.Select
strWMName = ActiveDocument.Sections(1).Index
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.HeaderFooter.Shapes.AddTextEffect(PowerPlusWaterMarkObject1, _
"DRAFT", "Arial", 1, False, False, 0, 0).Select
With Selection.ShapeRange

.Name = strWMName
.TextEffect.NormalizedHeight = False
.Line.Visible = False

With .Fill

.Visible = True
.Solid
.ForeColor.RGB = Gray
.Transparency = 0.5
End With

.Rotation = 315
.LockAspectRatio = True
.Height = InchesToPoints(2.42)
.Width = InchesToPoints(6.04)

With .WrapFormat
.AllowOverlap = True
.Side = wdWrapNone
.Type = 3

End With

.RelativeHorizontalPosition = wdRelativeVerticalPositionMargin
.RelativeVerticalPosition = wdRelativeVerticalPositionMargin
.Left = wdShapeCenter
.Top = wdShapeCenter
End With

ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

Exit Sub

ErrHandler:
MsgBox "An error occured trying to insert the watermark." & Chr(13) & _
"Error Number: " & Err.Number & Chr(13) & _
"Decription: " & Err.Description, vkOKOnly + vbCritical, "Error"


End Sub


Sub RemoveWaterMark()
Dim strWMName As String

On Error Goto ErrHandler

ActiveDocument.Sections(1).Range.Select
strWMName = ActiveDocument.Sections(1).Index
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Selection.HeaderFooter.Shapes(strWMName).Select
Selection.Delete
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

Exit Sub


ErrHandler:
MsgBox "An error occured trying to remove the watermark." & Chr(13) & _
"Error Number: " & Err.Number & Chr(13) & _
"Decription: " & Err.Description, vkOKOnly + vbCritical, "Error"

End Sub

Duane
08-18-2004, 03:43 PM
James, a watermark is another great idea. These routines to insert and delete the watermark would also work wonders.

Thanks much!

jamescol
08-18-2004, 03:45 PM
Oh my gosh!

I just realized that James and I are talking about 2 different kinds of "text boxes."

James is talking about the kind you can insert using the Forms toolbar, and I am talking about the "Text Box" you can insert using the Drawing toolbar OR BY going to "Edit" (on the regular old menu bar at the top of the Word screen) then "Text Box."

Perhaps Duane can verify, but I think Duane is using the "drawing" type of textbox because Duane's macro mentions:
ActiveDocument.Shapes

hmmm....


Kelly,
Good catch! I think you are correct, and Duane's admin is using the Drawing textbox. I don't even use Word's drawing features, and didn't consider anything other than a Form textbox.

James

lucas
08-22-2004, 11:29 AM
James,

I tried your "insert-remove watermark" code on Word 2000 and although I didn't receive an error, the word draft came up off center to the left, almost off of the page. It looked like a useful code so I highighted this line:
.RelativeHorizontalPosition
and hit f1. Did a little reading and changed the code in this section from:

.RelativeHorizontalPosition = wdRelativeVerticalPositionMargin
.RelativeVerticalPosition = wdRelativeVerticalPositionMargin

to


.RelativeHorizontalPosition = wdRelativeVerticalPositionPage
.RelativeVerticalPosition = wdRelativeVerticalPositionPage

Do you see any problem with this change as it seemed to solve the problem and the word Draft is centered on my pages...? my margins are set to the default(I have never changed them)

jamescol
08-22-2004, 11:38 AM
Lucas,
I don't see any obvious problems to your changes. The only thing that comes to mind is that when aligning against the page, sometimes the text (image, table, whatever) falls outside the printable page area.

It's curious that the margin alignment didn't work for you. Sounds like you right and left margins are actually off-kilter. Maybe you could post a copy of you document and I can take a look at it.

James

lucas
08-22-2004, 11:45 AM
It's curious that the margin alignment didn't work for you. Sounds like you right and left margins are actually off-kilter. Maybe you could post a copy of you document and I can take a look at it.

James
James,
attached is my Word 2000 .doc file. Thanks for taking a look.

jamescol
08-22-2004, 01:48 PM
Lucas,
The macro worked fine on my system for both Word XP and Word '03 using the margin alignment. It does appear that your margins are properly set, and I do not see any other reason the code would cause the problem you report.

Maybe we can get someone with Word 2000 to take a look at it and see if they can repro the behavior.

James

lucas
08-22-2004, 05:34 PM
James,

It is a handy piece of code. Might be worthy of a submission to the kb when you figure out whats going on with Word 2000. I'm pretty happy with it the way it is. Thanks for sharing.

TonyJollans
08-22-2004, 09:22 PM
The behaviour is very odd in Word 2K. I can reproduce it but can't explain it.
I did wonder if wdRelativeVerticalPositionMargin should have been wdRelativeHorizontalPositionMargin but it made no difference. I'll take another look later.

fumei
08-23-2004, 07:37 AM
Here again, is this bleeping problem with people using the word "textbox". The drawing "textbox" (although created by Insert > Textbox) is NOT a textbox. It is a graphic placeholder that may or may not contain text.

Regrading the original post.

1. People, people, people. Do not, EVER, retain Word's original names for formfields. They are dynamically named. If You have three textboxes (formfield textboxes). Text1, Text2, and Text3. You have code that retuns the .Result from Text2. It will return .Result from the SECOND textbox, regardless of what that is. if you have moved a textbox, or deleted a textbox, the names are dynamically changed. If Text3 is moved in sequence, it automatically becomes Text2 - and any code will run regarding that. All formfields are named by Word in the sequence are they currently in, NOT the sequence they were created. Always explicitly name them.

Back to the original post.

Esentially I see the design as follows. There is an area in the document that shows the text "Draft". It can be anywhere. At some point an admin needs to remove that text.

There are two very simple solutions. One very straightforward, tge other more code, but cool.

1. Type in the text "Draft" where ever you want. No textbox, no "textbox". Just text. Select the text. Go Inset > Bookmarks. Type in "draft_mark" (or whatever you like - one word though). Click Add.

Make a macro with a keyboard shortcut that has the following code.

ActiveDocument.Bookmarks("draft_mark").Delete

When the admin is ready, hit the keyboard shortcut. Done - the Draft text is removed. And this does not use those awful silly Shapes collection. They are not designed for text. There is no need for them for text..in my opinionated opinion.

2. Use ActiveX objects, not InLine Shapes, OR formfields. Have a ActiveX textbox (and yes it really is a textbox), Fill it with text "DRAFT". Make sure it is properly named! Have an ActiveX commandbutton - or you could use a regular code button on the toolbar - the choice is yours. In anycase, a button that fires a delete event on the ActiveX textbox. The commandbutton could have logic attached that validates the user. If they are not the admin. it will refuse to fire.

For ease, #1 is best. Bookmarks...and all that "textbox" crap can be ignored.

TonyJollans
08-24-2004, 04:25 PM
I've just had a bit of a play with the watermark in 2000.

I may just be imagining this but what appears to happen when the watermark is horizontally centred relative to the margin is that the centre of the watermark is aligned with the 'centre' of the left margin - that is half way between the left edge of the page and the left margin. So if the left margin is set to 2", the centre of the watermark is 1" to the right of the left edge and 1" to the left of the left margin. I can't think of any reason anyone would actually want to do this but, hey, what do I know?