Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 45 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
45
Dung lượng
8,21 MB
Nội dung
Word Procedures page 256 Office VBA: Macros You Can Use Today Wrd 'Variable declaration¶ Dim frm As frmUserInput¶ Dim doc As Word.Document¶ Set doc = ActiveDocument¶ If doc.Bookmarks.Count < 1 Then¶ MsgBox "Invalide document. " & _¶ "No bookmarks could be found.", _¶ vbCritical + vbOKOnly¶ Exit Sub¶ End If¶ Set frm = New frmUserInput¶ GetDataFromDocument frm, doc¶ frm.Show¶ If frm.Tag = "OK" Then¶ PutDataIntoDocument frm, doc¶ End If¶ Unload frm¶ If doc.Bookmarks.Exists("txtStartBody") Then¶ doc.Bookmarks("txtStartBody").Range.Select¶ End If¶ End Sub¶ ' * * * * *¶ Sub GetDataFromDocument(frm As UserForm, doc As Word.Document)¶ 'Variable declaration¶ Dim ctl As MSForms.Control¶ Dim firstControl As Boolean¶ For Each ctl In frm.Controls¶ If doc.Bookmarks.Exists(ctl.Name) Then¶ ctl.Text = doc.Bookmarks(ctl.Name).Range.Text¶ If Not firstControl Then¶ ctl.SelStart = 0¶ ctl.SelLength = Len(ctl.Text)¶ firstControl = True¶ End If¶ End If¶ Next¶ End Sub¶ ' * * * * *¶ Sub PutDataIntoDocument(frm As UserForm, doc As Word.Document)¶ 'Variable declaration¶ Dim ctl As MSForms.Control¶ Dim rng As Word.Range¶ For Each ctl In frm.Controls¶ If doc.Bookmarks.Exists(ctl.Name) Then¶ Set rng = doc.Bookmarks(ctl.Name).Range¶ rng.Text = ctl.Text¶ doc.Bookmarks.Add Name:=ctl.Name, Range:=rng¶ End If¶ Next¶ End Sub¶ Word Procedures Office VBA: Macros You Can Use Today page 257 Wrd Follow these steps: 1. Copy the macro code to the correspondence template's VBA project. 2. Transfer the UserForm frmUserInput to the same project using either the Organizer, or by dragging it in the Visual Basic Editor (VBE) to the template's project. The code for this UserForm module is below for reference. View the Appendix to learn how to store this procedure in a UserForm. Option explicit¶ ' * * * * *¶ Private Sub btnCancel_Click()¶ Me.Hide¶ Me.Tag = "Cancel"¶ End Sub¶ ' * * * * *¶ Private Sub btnOK_Click()¶ Me.Hide¶ Me.Tag = "OK"¶ End Sub¶ The code in the example file also includes the 'basCreateBookmark' module, which is utilized in the Creating a Bookmark from a Selection entry found on page 260. It is included below for reference. Option explicit¶ ' * * * * *¶ Const varName As String = "BookmarkCounter"¶ Const varDuplicateName As String _¶ = "DuplicateBookmarkCounter"¶ ' * * * * *¶ Sub CreateBookmark()¶ 'Variable declaration¶ Dim rng As Word.Range¶ Dim BookmarkName As String¶ Dim var As Word.Variable¶ 'Check whether the document variable that stores¶ 'a counter for bookmarks without content exists¶ If varExists(ActiveDocument, varName) = False Then¶ 'If not, create it and assign it the value 1¶ ActiveDocument.Variables.Add _¶ Name:=varName, Value:="1"¶ End If¶ Set var = ActiveDocument.Variables(varName)¶ Set rng = Selection.Range¶ If Selection.Type = wdSelectionIP Then¶ Word Procedures page 258 Office VBA: Macros You Can Use Today Wrd 'The user didn't select any text; a bookmark without¶ 'content will be inserted with¶ 'an incremented name txt#¶ 'Calculate that name¶ BookmarkName = "txt" & var.Value¶ var.Value = CStr(CLng(var.Value) + 1)¶ 'Alternately, a prompt can be displayed¶ 'to ask the user for the name¶ 'Uncomment the next two lines to use that method¶ 'BookmarkName = InputBox( _¶ 'No text is selected. Type in a bookmark name.")¶ Else¶ 'Get the bookmark name based on the selected text¶ BookmarkName = ProcessBookmarkName(rng.Text)¶ End If¶ 'Check if the bookmark name already exists;¶ 'if it does it will be incremented with a counter¶ BookmarkName = "txt" & CheckIfDuplicateName( _¶ ActiveDocument, BookmarkName)¶ 'Insert the bookmark¶ ActiveDocument.Bookmarks.Add _¶ Name:=BookmarkName, Range:=rng¶ End Sub¶ ' * * * * *¶ Function ProcessBookmarkName(s As String) As String¶ 'Variable declaration¶ Dim i As Long¶ 'Maximum length of a bookmark name is 40 characters¶ 'Because txt will be added to the beginning¶ 'therefore cut off at 37¶ If Len(s) > 37 Then s = Left(s, 37)¶ 'Replace all spaces with underline characters¶ s = Replace(s, " ", "_")¶ 'Remove any numbers at the beginning¶ Do While IsNumeric(Left(s, 1)) = True¶ s = Mid(s, 2)¶ Debug.Print s¶ Loop¶ 'Remove invalid characters¶ '(following list is not comprehensive)¶ For i = 1 To Len(s)¶ Select Case Mid(s, i, 1)¶ Case "§", "°", "+", "¦", "@", Chr$(34), "*", _¶ "#", "%", "&", "", "/", "|", "(", "¢", ")", _¶ "=", "?", "'", "´", "^", "`", "~", "[", "]", _¶ "¨", "!", "{", "}", "$", "£", "<", ">", "<", _¶ ".", ",", ":", ";", "-"¶ s = Left(s, i - 1) & Mid(s, i + 1)¶ Case Else¶ 'Otherwise, do nothing¶ End Select¶ Word Procedures Office VBA: Macros You Can Use Today page 259 Wrd Next i¶ ProcessBookmarkName = s¶ End Function¶ ' * * * * *¶ Function CheckIfDuplicateName(doc As Word.Document, _¶ BookmarkName As String) As String¶ 'Variable declaration¶ Dim var As Word.Variable¶ If varExists(doc, varDuplicateName) = False Then¶ ActiveDocument.Variables.Add _¶ Name:=varDuplicateName, Value:="1"¶ End If¶ Set var = ActiveDocument.Variables(varDuplicateName)¶ If doc.Bookmarks.Exists(BookmarkName) Then¶ 'Calculate incremented name¶ BookmarkName = Left(BookmarkName, _¶ Len(BookmarkName) - Len(var.Value)) & var.Value¶ var.Value = CStr(CLng(var.Value) + 1)¶ End If¶ CheckIfDuplicateName = BookmarkName¶ End Function¶ ' * * * * *¶ Function varExists(doc As Word.Document, _¶ s As String) As Boolean¶ 'Variable declaration¶ Dim var As Word.Variable¶ varExists = False¶ 'Loop through the list of document variables¶ 'and check whether it already exists by¶ 'comparing the name¶ For Each var In doc.Variables¶ If var.Name = s Then¶ varExists = True¶ Exit For¶ End If¶ Next var¶ End Function¶ 3. Create bookmarks in the template where the data items in the form should be inserted (select the location, then Insert | Bookmark). The bookmark names should match the names of the text boxes in the UserForm. Some of the text boxes used in the example are txtRecipient, txtStreetAddress, and txtCity. 4. To see and change the text box names in the Visual Basic Editor (VBE), click on a text box and then look at the Name information in the Properties window (it is usually the first entry listed). Type the correct name in the box if changes need to be made. Word Procedures page 260 Office VBA: Macros You Can Use Today Wrd Tip: See the following entry, Creating a Bookmark from a Selection, for a tool to quickly create bookmarks from text selections. 5. Insert a bookmark named txtStartBody in the location where the user should start typing once the macro has finished. Deciding not to use a bookmark simply means that the macro skips selecting that location if a bookmark isn't present. 6. Feel free to change the form to fit various requirements. Deleting and adding labels and text boxes won’t detrimentally affect the macro tool. Just be careful not to delete the buttons. 7. This tool contains an 'AutoNew' procedure so that the form appears whenever the user creates a new document from the template. Comment out the procedure if this is unwanted. 8. To make it easy to edit the input at a later time, assign the procedure 'GetUserInput' to a toolbar button. The macro automatically picks up the bookmarked content when it displays the user form. Creating a Bookmark from a Selection This procedure creates a bookmark from the current selection in a document and bases the bookmark name on the selected text. Example file: W038 Scenario: Using a macro to place text into a Word document, whether the text originates from a UserForm, a database, or an InputBox, requires that a target be specified in the document. Most often, bookmarks serve as targets. Bookmarks are also used to mark information for cross- referencing and generating Tables of Content for specific parts of a document. While creating bookmarks is simple enough—select a range of characters, then Insert | Bookmark, type in a name and click Insert—it is time-consuming to repeatedly go through the menu and display the dialog box. Word Procedures Office VBA: Macros You Can Use Today page 261 Wrd The following macro bookmarks the current selection in the document, using the selected text as the bookmark name. If the selection is long, only the first 40 characters (maximum number of characters for a bookmark name) are used. Invalid characters will be removed, according to the following rules: ¾ Bookmark names may not begin with numbers. Any numbers at the beginning of a selection are cut off from the bookmark name. ¾ Punctuation, such as periods and commas, are not allowed and are removed. ¾ Spaces are replaced with underscores. View the Appendix to learn how to store this procedure in a Standard module. Option explicit¶ ' * * * * *¶ Const varName As String = "BookmarkCounter"¶ Const varDuplicateName As String _¶ = "DuplicateBookmarkCounter"¶ ' * * * * *¶ Sub CreateBookmark()¶ 'Variable declaration¶ Dim rng As Word.Range¶ Dim BookmarkName As String¶ Dim var As Word.Variable¶ 'Check whether the document variable that stores¶ 'a counter for bookmarks without content exists¶ If varExists(ActiveDocument, varName) = False Then¶ 'If not, create it and assign it the value 1¶ ActiveDocument.Variables.Add _¶ Name:=varName, Value:="1"¶ End If¶ Set var = ActiveDocument.Variables(varName)¶ Set rng = Selection.Range¶ If Selection.Type = wdSelectionIP Then¶ 'The user didn't select any text; a bookmark without¶ 'content will be inserted with¶ 'an incremented name txt#¶ 'Calculate that name¶ BookmarkName = "txt" & var.Value¶ var.Value = CStr(CLng(var.Value) + 1)¶ 'Alternately, a prompt can be displayed¶ 'to ask the user for the name¶ 'Uncomment the next two lines to use that method¶ 'BookmarkName = InputBox( _¶ 'No text is selected. Type in a bookmark name.")¶ Else¶ 'Get the bookmark name based on the selected text¶ Word Procedures page 262 Office VBA: Macros You Can Use Today Wrd BookmarkName = ProcessBookmarkName(rng.Text)¶ End If¶ 'Check if the bookmark name already exists;¶ 'if it does, it is incremented with a counter¶ BookmarkName = "txt" & CheckIfDuplicateName( _¶ ActiveDocument, BookmarkName)¶ 'Insert the bookmark¶ ActiveDocument.Bookmarks.Add _¶ Name:=BookmarkName, Range:=rng¶ End Sub¶ ' * * * * *¶ Function ProcessBookmarkName(s As String) As String¶ 'Variable declaration¶ Dim i As Long¶ 'Maximum length of a bookmark name is 40 characters¶ 'Because txt will be added to the beginning¶ 'therefore cut off at 37¶ If Len(s) > 37 Then s = Left(s, 37)¶ 'Replace all spaces with underline characters¶ s = Replace(s, " ", "_")¶ 'Remove any numbers at the beginning¶ Do While IsNumeric(Left(s, 1)) = True¶ s = Mid(s, 2)¶ Debug.Print s¶ Loop¶ 'Remove invalid characters¶ '(following list is not comprehensive)¶ For i = 1 To Len(s)¶ Select Case Mid(s, i, 1)¶ Case "§", "°", "+", "¦", "@", Chr$(34), "*", _¶ "#", "%", "&", "", "/", "|", "(", "¢", ")", _¶ "=", "?", "´", "^", "`", "~", "[", "]", _¶ "¨", "!", "{", "}", "$", "£", "<", ">", "<", _¶ ".", ",", ":", ";", "-"¶ s = Left(s, i - 1) & Mid(s, i + 1)¶ Case Else¶ 'Otherwise, do nothing¶ End Select¶ Next i¶ ProcessBookmarkName = s¶ End Function¶ ' * * * * *¶ Function CheckIfDuplicateName(doc As Word.Document, _¶ BookmarkName As String) As String¶ 'Variable declaration¶ Dim var As Word.Variable¶ If varExists(doc, varDuplicateName) = False Then¶ ActiveDocument.Variables.Add _¶ Name:=varDuplicateName, Value:="1"¶ End If¶ Set var = ActiveDocument.Variables(varDuplicateName)¶ Word Procedures Office VBA: Macros You Can Use Today page 263 Wrd If doc.Bookmarks.Exists(BookmarkName) Then¶ 'Calculate incremented name¶ BookmarkName = Left(BookmarkName, _¶ Len(BookmarkName) - Len(var.Value)) & var.Value¶ var.Value = CStr(CLng(var.Value) + 1)¶ End If¶ CheckIfDuplicateName = BookmarkName¶ End Function¶ ' * * * * *¶ Function varExists(doc As Word.Document, _¶ s As String) As Boolean¶ 'Variable declaration¶ Dim var As Word.Variable¶ varExists = False¶ 'Loop through the list of document variables¶ 'and check whether it already exists by¶ 'comparing the name¶ For Each var In doc.Variables¶ If var.Name = s Then¶ varExists = True¶ Exit For¶ End If¶ Next var¶ End Function¶ Follow these steps: 1. Copy the entire set of macros to a module in the document, in its template, in Normal.dot, or in any template that will be loaded as a global Add-in. Then assign it to a toolbar button and/or keyboard shortcut. See Running a Macro from a Toolbar Button on page 418 or Running a Macro Using Shortcut Keys on page 419 for help in assigning a macro to a toolbar button or a keyb oard shortcut. 2. The incremental numbers for duplicate names and bookmarks without content are stored in document Variables. The names for the Variables are set as Const values at the beginning of the module. To use different names, change the values in quotation marks. 3. To type in a bookmark name when no text is selected to provide the bookmark name, remove the apostrophes from the lines of code below, and comment out the original code: If Selection.Type = wdSelectionIP Then¶ 'The user didn't select any text; a bookmark without¶ 'content will be inserted with¶ 'an incremented name txt#¶ 'Calculate that name¶ BookmarkName = "txt" & var.Value¶ var.Value = CStr(CLng(var.Value) + 1)¶ 'Alternately, a prompt can be displayed¶ Word Procedures page 264 Office VBA: Macros You Can Use Today Wrd 'to ask the user for the name¶ 'Uncomment the next two lines to use that method¶ 'BookmarkName = InputBox( _¶ 'No text is selected. Type in a bookmark name.")¶ Else¶ Making Bookmarks Visible With this procedure, you can highlight bookmarks in a document and place their names in comments to make them easier to manage. Example file: W039 Tip: In Word 2002 and 2003, comments can be displayed in the right margin, with connecting lines. In Word 97, Word 2000, and Word 2003, the bookmark name appears in tip flags when the mouse hovers over a comment. View the Appendix to learn how to store this procedure in a Standard module. Option explicit¶ ' * * * * *¶ Sub HighLightBookmarks()¶ 'Variable declaration¶ Dim bkm As Word.Bookmark¶ Dim rng As Word.Range¶ For Each bkm In ActiveDocument.Bookmarks¶ Set rng = bkm.Range¶ rng.HighlightColorIndex = wdYellow¶ ActiveDocument.Comments.Add _¶ Range:=rng, Text:=bkm.Name¶ Set rng = Nothing¶ Next bkm¶ End Sub¶ ' * * * * *¶ Sub RemoveHighlighting()¶ If Selection.Type = wdSelectionIP Then¶ ActiveDocument.Range.HighlightColorIndex = wdNoHighlight¶ ElseIf Selection.Type = wdSelectionNormal Then¶ Scenario: When setting up a document with many bookmarks, it is often difficult to keep track of their locations and names. One way to obtain an overview is to highlight them, and put their names in comments. Word Procedures Office VBA: Macros You Can Use Today page 265 Wrd Selection.Range.HighlightColorIndex = wdNoHighlight¶ Else¶ MsgBox "No text is selected."¶ End If¶ End Sub¶ To change the highlight color, delete the text = wdYellow; type the equals sign (=) again, and a list of values should appear. Select one of the values and press Enter. Forcing the User to Enable Macros These procedures provide methods to prevent users from successfully working with a document if macros are not enabled. Example file: WordProtection.doc, DocFromCode.doc, WeeklyReport.xls Generating the Document Using VBA Certainly, the most effective way is to generate the entire document when it is opened or created from a template. The 'Document_Open' and 'AutoOpen' procedures fire when a document is opened. A 'Document_New' or 'AutoNew' procedure fires when a new document is created from a template. In the document body, place a message telling the user how to enable macro security so that the document can be created. If macros can be run, a macro removes the message text and replaces it with the document, as shown by the following sample code. Tip: To open one of the sample documents without the AutoOpen macros running, hold down the Shift key while it is opening. Holding the Shift key down when opening a file prevents macros from executing. If this step is forgotten (happens all the time), just close the document without saving the changes and try again. Scenario: When distributing macros that manage templates or documents, it is important that the user have macros enabled; otherwise the macros won't work. For obvious reasons, it is not possible to create a macro that changes macro security settings; if it were, macro security would be useless. This section discusses a number of ways to prevent the user from working with a project unless macros are enabled. There are a couple of code examples to demonstrate how the techniques are applied. [...]... macro security for other documents your code might need to open If the user has set macro security to "Medium", a prompt appears if any files opened by the code contain macros This can be irritating to the user if Office VBA: Macros You Can Use Today page 2 67 Wrd Word Procedures the solution should run without interruption Or, it may be that open files should not have any macros they contain execute A new... CreateObject("Scripting.FileSystemObject")¶ Office VBA: Macros You Can Use Today page 271 Outlook Procedures Out 'Create target directory object that is used for saving¶ 'attachments¶ Set fld = fso.GetFolder(SelectFolder)¶ 'Set objApp object¶ Set objApp = Outlook.Application¶ 'Set source folder as the currently activated folder¶ Set objFolder = objApp.ActiveExplorer.CurrentFolder¶ 'Confirmation¶ If MsgBox("Do you want to extract... itemAttc¶ End If¶ Next objItem¶ 'Inform user about completion and saved number¶ 'of attachment¶ MsgBox i & " attachments have been succesfully saved in " _¶ & fld.path¶ ExitSub:¶ 'Release object variables and memory¶ Set fso = Nothing¶ Set objApp = Nothing¶ Exit Sub¶ page 272 Office VBA: Macros You Can Use Today Outlook Procedures ErrHandler:¶ Select Case Err.Number¶ Case 76 'Target directory doesn't exist¶... category to tell the macro that the code should process a Task Item is necessary The ‘Daily Report Sender’ category name is used in this sample code Office VBA: Macros You Can Use Today page 2 87 Out Outlook Procedures Create the Task Item as shown on the following page: Out Figure 72 – Creating a Recurrent Task The Sample Task Item has been set by using a reminder to recur everyday at 06:00 PM Two sample... page 266 Office VBA: Macros You Can Use Today Word Procedures View the Appendix to learn how to store this procedure in the ThisDocument module Option explicit¶ ' * * * * *¶ Private Sub Document_Open()¶ GenerateDocument¶ End Sub¶ Using Forms Protection Generating an entire document from scratch can be a challenge Somewhat easier is the method of protecting the file as a Word form (don’t confuse this... Application.AutomationSecurity = msoAutomationSecurityForceDisable¶ End Sub¶ page 268 Office VBA: Macros You Can Use Today Outlook Procedures Outlook Procedures By Suat Ozgur Most of the Outlook procedures do not have sample files because Outlook does not store its procedures in files Creating Control Buttons This procedure automatically creates control buttons with VBA code The following code shows how to create a custom control... statement of SQL¶ 'in requested connection¶ objRs.Open "SELECT * " & _¶ "FROM " & tblName & _¶ " WHERE EntryID=" & Chr(34) & _¶ objContact.EntryID & Chr(34), objConn, 2, 3¶ With objRs¶ Office VBA: Macros You Can Use Today Out page 277 Outlook Procedures Out 'Verify if contact already exists in the table¶ If EOF Then¶ 'New contact, start new record¶ AddNew¶ End If¶ 'Set field values¶ Fields(0).Value = objContact.EntryID¶... With¶ MsgBox "Access database has been opened."¶ ErrHandler:¶ If Err.Number = 429 Then¶ 'MS Access is not installed in this system¶ MsgBox "You must have MS Access installed to " & _¶ "open database in Access." & vbCrLf & _¶ page 278 Office VBA: Macros You Can Use Today Outlook Procedures "Database Path : " & strFileName, _¶ vbOKOnly + vbExclamation, "Error"¶ ElseIf Err Then¶ 'Another critical error¶... each recipient over a period of time Example file: O005.xls This application lets the user select a saved mail item in the Drafts folder to send to the addresses listed in an Excel worksheet; it is triggered from Excel, not Outlook itself page 282 Office VBA: Macros You Can Use Today Outlook Procedures Out Figure 71 – Sending E-mail Messages to Multiple Recipients View the Appendix to learn how to... Button").Delete False¶ End Sub¶ page 270 Office VBA: Macros You Can Use Today Outlook Procedures Sa v i n g E- ma il A tta ch men ts in a S pecif ied Folder This macro saves all e-mail attachments in the active Outlook folder into the specified folder It automatically renames the saved files in the folder by producing auto-incremented version numbers Scenario: You sent out a questionnaire to 1,000 . Procedures Office VBA: Macros You Can Use Today page 2 57 Wrd Follow these steps: 1. Copy the macro code to the correspondence template's VBA project. 2. Transfer the UserForm frmUserInput. 'Alternately, a prompt can be displayed¶ Word Procedures page 264 Office VBA: Macros You Can Use Today Wrd 'to ask the user for the name¶ 'Uncomment the next two lines to use that method¶. that macro. This entry solves your dilemma. Outlook Procedures page 272 Office VBA: Macros You Can Use Today Out 'Create target directory object that is used for saving¶ 'attachments¶