Lập trình VBA for word (tiếng anh)

CHAPTER 1: Beginners' tips. 10

1. How to modify a recorded macro . 10

1.1. What's wrong with the recorder, anyway?. 10

1.2. Cleaning out unneeded dialog arguments. 10

1.3. Making a macro more general . 11

2. Making toggle macros. 13

2.1. Fixing broken Replace macros. 13

2.2. Naming and storing macros . 14

2.3. More fun to come. 15

3. Creating a macro with no programming experience using the recorder. 15

4. Getting to grips with VBA basics in 15 minutes. 17

5. Making the transition from WordBasic to VBA . 22

6. Organizing your macros . 23

6.1. Getting yourself organized. 23

6.2. Editing Macros. 24

6.3. Organizing your Global Templates. 24

7. When to use parentheses to enclose subroutine and function arguments. 26

8. The art of defensive programming . 27

Recommended further reading. 30

9. How to cut out repetition and write much less code, by using subroutines and functions that

take arguments . 31

10. How to use a single VBA procedure to read or write both custom and built-in Document

Properties . 34

10.1. Writing Document Properties . 34

10.2. Reading Document Properties . 36

11. How to get the username of the current user. 37

12. How can I get a list of the available printer names? . 38

13. How to find out, using VBA, how many replacements Word made during a Find & Replace

All. 40

14. Finding and replacing symbols . 43

14.1. Basic Latin symbols listed under “(normal text)” . 44

14.2. Upper Unicode characters and symbols which use decorative fonts. 44

14.3. How to write your own macro to do the job. 45

15. Distributing macros to other users . 48

CHAPTER 2: Returning information. 50

1. How to check whether Word is open. 50

2. Control Word from Excel. 50

3. Determine whether the insertion point is located at the end of a document. 52

pdf221 trang | Chia sẻ: gaobeo18 | Lượt xem: 940 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Lập trình VBA for word (tiếng anh), để xem tài liệu hoàn chỉnh bạn click vào nút TẢI VỀ ở trên
 especially in the case of numbering styles, where it can sometimes destroy the link 
between the styles and their List Templates. 
But the good news is that updating styles can be made reliable, as follows. 
1. For it to be reliable, your numbering styles must use named List Templates. See the links at How 
to cure Word's List Numbering with a dose of VBA for more details. 
2. All the styles in the “Styles in Use” list need to have been physically applied to text in the 
template once (but they do not need to have been applied in documents based on the template). 
What the difference is, in terms of the flags stored inside a template file, between a style that is 
listed in the “In use” list but has never been applied to text, and one that has been applied, is a 
mystery; but it seems there is a difference. 
Unfortunately, it is all too easy to add a style to the “Styles in Use” list without ever applying 
the style to any text. In the case of built-in styles, you can do this manually by selecting Format 
+ Style, where it says “List”, select “All styles”, and click Modify + OK + Close. Or 
programmatically, you can add it to the “In use” list by running code that defines the style. 
In the case of custom styles, you can add them to the “In use” list without applying them to text 
by selecting Format + Style + New + OK + Close; or programmatically, by defining a new 
style without applying it. 
Styles (especially numbering styles) that are listed in the “In use” list of a template, but have 
never physically been applied to text, will not be stable if you update your styles from the 
template. So if in doubt, it is a good idea to insert a dummy paragraph in each of your templates, 
cycle it through all the styles in the template's “In use” list, delete the dummy paragraph, and 
save the template. And if you subsequently need to redefine any of the styles in the template, it 
is again a good idea to apply the redefined style to a dummy paragraph. 
3. Sometimes, you have to do the update twice or occasionally even three times in order preserve 
your List Template names and their links to your numbering styles: 
Dim oLT As ListTemplate 
Lập trình VBA for Word 
Nơi phát hành: www.giaiphapexcel.com 
217 
ActiveDocument.UpdateStyles 
ActiveDocument.UpdateStyles 
On Error Resume Next 
For Each oLT In ActiveDocument.AttachedTemplate.ListTemplates 
 If Not oLT.Name = "" Then 
 If Not ActiveDocument.ListTemplates(oLT.Name).ListLevels(1) _ 
 .LinkedStyle = oLT.ListLevels(1).LinkedStyle Then 
 ActiveDocument.UpdateStyles 
 Exit For 
 End If 
 End If 
Next oLT 
No theories as to why this might be; it's a bug; but at least there is a workaround. 
You can make the Tools + Templates and Add-ins dialog safe for users to use by intercepting 
the Word command as follows: 
Sub FileTemplates() 
With Dialogs(wdDialogToolsTemplates) 
 .Show 
 If .LinkStyles = 1 Then 
 ActiveDocument.UpdateStyles 
 Dim oLT As ListTemplate 
 On Error Resume Next 
 For Each oLT In ActiveDocument.AttachedTemplate.ListTemplates 
 If Not oLT.Name = "" Then 
 If Not 
ActiveDocument.ListTemplates(oLT.Name).ListLevels(1) _ 
 .LinkedStyle = oLT.ListLevels(1).LinkedStyle 
Then 
 ActiveDocument.UpdateStyles 
 Exit For 
 End If 
 End If 
 Next oLT 
 ActiveDocument.UpdateStylesOnOpen = False 
 End If 
End With 
End Sub 
[The ActiveDocument.UpdateStylesOnOpen = False line in the above code sample prevents the 
user from being able to save the document with the “Automatically update document styles” 
setting switched on; and means they don't have to immediately go back to the dialog every time 
they update their styles, simply in order to deselect that setting. If that's not what you want, 
though, you can remove that line. But if you do remove that line, then you will also need to have 
an AutoOpen macro that checks whether the setting is switched on, and if it is, that updates the 
styles again if need be; otherwise the numbering styles will sometimes be broken when the 
Lập trình VBA for Word 
Nơi phát hành: www.giaiphapexcel.com 
218 
document is reopened.] 
But unfortunately, the Dialogs(wdDialogToolsTemplates) object is buggy – the dialog it 
displays doesn't show the list of add-ins, and half the buttons on it are greyed out. This is well 
worth emailing mswish@microsoft.com about. 
You can get round this as follows: 
a) Instead of intercepting the FileTemplates command, create the following macro: 
Sub ReplacementToolsTemplatesAndAddins() 
'Execute the built-in button 
CommandBars.FindControl(ID:=751).Execute 
If Dialogs(wdDialogToolsTemplates).LinkStyles = 1 Then 
 Dim oDoc As Document, oLT As ListTemplate 
 Set oDoc = ActiveDocument 
 oDoc.UpdateStyles 
 On Error Resume Next 
 For Each oLT In oDoc.AttachedTemplate.ListTemplates 
 If Not oLT.Name = "" Then 
 If Not oDoc.ListTemplates(oLT.Name).ListLevels(1) _ 
 .LinkedStyle = oLT.ListLevels(1).LinkedStyle 
Then 
 oDoc.UpdateStyles 
 Exit For 
 End If 
 End If 
 Next oLT 
 oDoc.UpdateStylesOnOpen = False 
End If 
End Sub 
(Again, remove the ActiveDocument.UpdateStylesOnOpen = False line if you don't want it.) 
b) Create a new toolbar, name it “Hidden”, and move the built-in “Templates and Add-ins” 
button to the new toolbar. This is in order that the above macro can execute the built-in 
button (doing so avoids the bugs that you get if you use Dialogs(wdDialogToolsTemplates)), 
without the built-in button being visible to the user. 
c) Go to Tools + Customize, select the “Commands” tab; in the left pane, select “All macros”, 
in the right pane select the ReplacementToolsTemplatesAndAddins macro, and drag it onto 
the Tools menu, to where the “Templates and Add-ins” button used to be. Right-click the 
new button and rename it: 
Templates and Add-&Ins... 
d) Disable the new toolbar (which makes it invisible to the user), as follows: 
CommandBars("Hidden").Enabled = False 
e) If you've made the above customisations in an add-in, create an AutoExec macro as follows: 
Sub AutoExec() 
Lập trình VBA for Word 
Nơi phát hành: www.giaiphapexcel.com 
219 
 CommandBars("Hidden").Enabled = False 
End Sub 
Or if you've customized a template rather than an add-in, create an AutoNew and AutoOpen 
macro in the template, containing the same code. 
If you have already disabled the Web toolbar, of course, one could use that for this purpose, 
rather than creating a new Toolbar called “Hidden”. See also: How to stop the web toolbar 
from jumping up at you whenever you click on a page number in the table of contents. 
With one qualification, your users should now be able to update their styles from their 
template(s) safely. 
That one qualification is this: the above macro will safely update styles if their definitions have 
been changed in the attached template, and will safely revert them to the attached template's 
definitions if they have been redefined in the document. It will also safely update styles that are 
defined in the attached template but not in the document. But if there are broken list numbering 
styles in the document, it will sometimes, but not always, fix those. In other words, it is not a 
complete substitute for a “Fix numbering” macro (although it should greatly reduce the 
frequency with which you'll need to run the latter). For details of the latter, see the links at How 
to cure Word's List Numbering with a dose of VBA. 
If you want to be able to update the styles of Word 97 documents that are attached 
to Normal.dot 
If instead of using the UpdateStyles method, you use CopyStylesFromTemplate, then you can 
update your document's styles even in Word 97, when the attached template is Normal.dot. 
However, using CopyStylesFromTemplate is significantly slower than using UpdateStyles; so the 
following variation on the above macro only uses the slower method when necessary, and uses 
UpdateStyles when possible: 
Sub ReplacementToolsTemplatesAndAddins() 
Dim Word97Normal As Boolean, oDoc As Document, oLT As ListTemplate 
'Execute the built-in button 
CommandBars.FindControl(ID:=751).Execute 
If Dialogs(wdDialogToolsTemplates).LinkStyles = 1 Then 
 Set oDoc = ActiveDocument 
 If Left$(Application.Version, 1) = "8" And _ 
 oDoc.AttachedTemplate = NormalTemplate Then 
 Word97Normal = True 
 End If 
 If Word97Normal Then 
 oDoc.CopyStylesFromTemplate NormalTemplate 
 oDoc.CopyStylesFromTemplate NormalTemplate 
 Else 
Lập trình VBA for Word 
Nơi phát hành: www.giaiphapexcel.com 
220 
 oDoc.UpdateStyles 
 End If 
 On Error Resume Next 
 For Each oLT In oDoc.AttachedTemplate.ListTemplates 
 If Not oLT.Name = "" Then 
 If Not oDoc.ListTemplates(oLT.Name).ListLevels(1) _ 
 .LinkedStyle = oLT.ListLevels(1).LinkedStyle Then 
 If Word97Normal Then 
 oDoc.CopyStylesFromTemplate NormalTemplate 
 Else 
 oDoc.UpdateStyles 
 End If 
 Exit For 
 End If 
 End If 
 Next oLT 
 oDoc.UpdateStylesOnOpen = False 
End If 
End Sub 
8. Scroll all open documents the same percentage as the active 
document 
Article contributed by Bill Coan 
Scroll the active document to the desired point, then run a macro that scrolls all other open 
documents to the same percentage. 
The following code is written for Word 97. It looks at how far you've scrolled the active window, 
then scrolls all other document windows the same percentage. Of course, if one document is 10 
pages long and another is 100 pages long, then a 50% vertical scroll would put you on page 5 in one 
document and page 50 in the other. 
Sub ScrollAllWindowsALike() 
Dim myWindow As Window 
Set myWindow = ActiveWindow 
ScrollPercent = myWindow.VerticalPercentScrolled 
For Each oWindow In Application.Windows 
 oWindow.Activate 
 oWindow.VerticalPercentScrolled = ScrollPercent 
Next oWindow 
myWindow.Activate 
End Sub 
Lập trình VBA for Word 
Nơi phát hành: www.giaiphapexcel.com 
221 

File đính kèm:

  • pdfLap trinh VBA for Word.pdf