Office VBA Macros You Can Use Today phần 5 ppsx

45 240 0
Office VBA Macros You Can Use Today phần 5 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Word Procedures page 166 Office VBA: Macros You Can Use Today Wrd ' * * * * *¶ Sub InsertPictureWithCaption()¶ 'Variable declaration¶ Dim FileToInsert As String¶ Dim rng As Word.Range¶ Dim frm As Word.Frame¶ FileToInsert = GetFileName¶ 'The user cancelled¶ If Len(FileToInsert) = 0 Then Exit Sub¶ Set rng = Selection.Range.Paragraphs(1).Range¶ 'When in a paragraph with text¶ 'move to the top, so that the frame¶ 'will be associated with this paragraph¶ 'and insert an empty paragraph¶ If Len(rng.Paragraphs(1).Range.Text) <> 1 Then¶ rng.Collapse wdCollapseStart¶ rng.Text = vbCr¶ End If¶ 'Put a frame around the paragraph¶ Set frm = rng.Frames.Add(rng)¶ 'format the frame¶ FormatFrame frm¶ 'Insert a picture into it¶ rng.InlineShapes.AddPicture _¶ FileName:=FileToInsert, _¶ LinkToFile:=LinkGraphic, _¶ SaveWithDocument:=SaveInDoc, _¶ Range:=rng¶ If frm Is Nothing Then¶ AddaCaptionInaFrame rng¶ Else¶ AddaCaptionInaFrame frm.Range¶ End If¶ 'Moves insertion point out of frame¶ Selection.MoveRight Unit:=wdCharacter, Count:=1¶ End Sub¶ ' * * * * *¶ Function GetFileName() As String¶ 'Variable declaration¶ Dim dlg As Word.Dialog¶ Set dlg = Dialogs(wdDialogInsertPicture)¶ With dlg¶ .Display¶ End With¶ GetFileName = dlg.Name¶ End Function¶ Word Procedures Office VBA: Macros You Can Use Today page 167 Wrd ' * * * * *¶ Function FormatFrame(ByRef frm As Word.Frame)¶ 'Set the borders¶ frm.Borders.Enable = False¶ If frm.Borders.Enable = True Then¶ With frm.Borders¶ .OutsideColorIndex = wdBlack¶ .OutsideLineStyle = wdLineStyleSingle¶ .OutsideLineWidth = wdLineWidth050pt¶ End With¶ End If¶ 'Determine how the frame sizes¶ 'The frame can size a picture proportionally¶ 'if an exact height OR width is set,¶ 'and let the other dimension size automatically¶ 'Use if the frame should be a certain height¶ frm.HeightRule = LimitPictureHeight¶ If LimitPictureHeight <> wdFrameAuto Then¶ frm.HeightRule = LimitPictureHeight¶ frm.Height = InchesToPoints(3)¶ End If¶ 'Use if the frame should be a certain width¶ frm.WidthRule = LimitPictureWidth¶ If LimitPictureWidth <> wdFrameAuto Then¶ frm.WidthRule = wdFrameAtLeast¶ frm.Width = InchesToPoints(1.5)¶ End If¶ frm.RelativeHorizontalPosition = _¶ wdRelativeHorizontalPositionColumn¶ frm.HorizontalPosition = wdFrameRight¶ 'Corresponds to "Move with text"¶ frm.RelativeVerticalPosition = _¶ wdRelativeVerticalPositionParagraph¶ frm.VerticalPosition = 0¶ frm.LockAnchor = False¶ frm.TextWrap = True¶ End Function¶ ' * * * * *¶ Sub AddaCaptionInaFrame(rng As Word.Range)¶ 'Move to the end of the frame¶ rng.Collapse wdCollapseEnd¶ 'Add a new line¶ rng.InsertAfter vbCr¶ 'Select just that line¶ If rng.Frames.Count = 1 Then¶ 'with frame¶ rng.Collapse wdCollapseEnd¶ Else¶ 'without frame¶ rng.Collapse wdCollapseStart¶ End If¶ Word Procedures page 168 Office VBA: Macros You Can Use Today Wrd rng.Select¶ 'Let the user add a caption¶ Dialogs(wdDialogInsertCaption).Show¶ End Sub¶ Making Changes You can change a number of items in this procedure. Linking in a Picture Use the following to specify how the graphic is inserted and saved in the document: Const LinkGraphic¶ Const SaveInDoc¶ In order to link to the file, set the first of these to True. In this case, the latter may be True or False (False will result in a smaller file size.) If Const LinkGraphic is set to False, then SaveInDoc must be set to True. Inserting a Picture Without a Frame To use the macro to simply insert pictures from the folder of choice, with default preferred settings, comment out the lines. Set frm = rng.Frames.Add(rng)¶ FormatFrame frm.¶ Leaving off the Caption To leave off the caption, comment out these lines by placing an apostrophe in front of each. If frm Is Nothing Then¶ AddaCaptionInaFrame rng¶ Else¶ AddaCaptionInaFrame frm.Range¶ End If¶ Word Procedures Office VBA: Macros You Can Use Today page 169 Wrd Controlling the Picture Size Inserting a picture into a frame, one side of which is set to an exact size, causes the picture to resize itself proportionally to fit. The other dimension should be set to "AutoFit". Set the Const LimitPictureWidth and Const LimitPictureHeight values to the combination of wdFrameAuto and wdFrameExact that is preferred. Setting Exact Height and Width Set the height and/or width in inches for the frame in the ‘FormatFrame’ procedure by changing the numbers in parentheses in these lines: frm.Height = InchesToPoints(3)¶ frm.Width = InchesToPoints(3)¶ Adding Borders Put a border around the frame by setting frm.Borders.Enable to True. Once this is done, the values under With frm.Borders takes effect. In order to change the color, line style, or line width, delete from the equals sign (=) to the end of the line. Then, type the equals sign again and Intellisense should show a list of values to choose from. Positioning the Frame The values for the following correspond to settings in the dialog box Format Frame. Here, again, deleting the equal sign and the text following it, then typing the equal sign again will present a list of valid values. RelativeHorizontalPosition HorizontalPosition RelativeVerticalPosition VerticalPosition Frames can be formatted relative to the page, both vertically and horizontally, or relative to the text to which they are anchored (equivalent to activating "Move with text"). Wrapping Text Around the Frame This is controlled by setting frm.TextWrap to True or False. Word Procedures page 170 Office VBA: Macros You Can Use Today Wrd Changing the Path for Graphics Files Change the path for the Const StartFolder to the folder where the graphics to be used are located. This won't disallow navigating to any other path; the Insert Picture dialog box simply uses this path as a starting point. To use the default file location set for a particular installation of Word, just remove the text between the quotes (but leave the quote pairs). Tips: This code is constructed modularly to make it easy to customize the way the macro works, so that it can best suit various needs. When using this macro with a caption, only set the width. Setting the height cuts off the caption. Associating a Picture with a Page Using a graphic’s name, this procedure moves that graphic to the page where it should always reside. Example file: W018 Scenario: Word for Windows was originally conceived in the late 1980s purely as a word processing program. As users' expectations increased, Microsoft added numerous layout capabilities to it. One piece of functionality it is still missing, however, is the ability to "lock" a graphical object to a particular page. Graphical objects formatted with text wrap are always anchored to a paragraph. They always appear on the same page as that paragraph. So even if an object has been positioned relative to the page (Move with text is turned off), as edits are made to the text, the object may move to another page. Although this is "expected behavior" in Word, it can be extremely irritating. Repositioning the graphics is time consuming and somewhat error prone. This tool can quickly reposition all graphics formatted with text wrap that are positioned relative to a page. It also includes a form for assigning names. Word Procedures Office VBA: Macros You Can Use Today page 171 Wrd View the Appendix to learn how to store this procedure in a Standard module. Option explicit¶ ' * * * * *¶ Sub ShowGraphicName()¶ frmNameGraphic.Show¶ End Sub¶ ' * * * * *¶ Sub MoveGraphicToPage()¶ 'Variable declaration¶ Dim shp As Word.Shape¶ Dim PageNr As Long¶ Dim iPos As Long¶ For Each shp In ActiveDocument.Shapes¶ 'Don't process canvas content¶ 'Only valid in Word 2002, 2003¶ If Not shp.Child Then¶ With shp¶ Select Case .RelativeVerticalPosition¶ 'Positioned relative to the page¶ Case wdRelativeVerticalPositionPage, _¶ wdRelativeVerticalPositionMargin¶ 'Extract the page number;¶ 'it's the 5th character in the name¶ iPos = 4¶ PageNr = ExtractNumber(shp.Name, iPos)¶ 'Compare the current page number with¶ 'the specified one¶ If shp.Anchor.Information(wdActiveEndPageNumber) _¶ <> Val(PageNr) Then¶ 'Move the graphic to the correct page¶ 'using the Clipboard¶ MoveGraphicViaClipboard shp, PageNr¶ End If¶ Case wdRelativeVerticalPositionLine, _¶ wdRelativeVerticalPositionParagraph¶ 'It's formatted to move with the text and¶ 'is therefore not linked with a specific page¶ Case Else¶ 'unknown Enum constant¶ End Select¶ End With¶ End If¶ Next shp¶ End Sub¶ ' * * * * *¶ 'Extract a number from a string,¶ 'Starting at the offset position plus1¶ 'until there are no more numerals¶ Function ExtractNumber(ByVal sString As String, _¶ Word Procedures page 172 Office VBA: Macros You Can Use Today Wrd ByVal Offset As Long) As Long¶ 'iNr is declared as type "Variant" because¶ 'it can contain numbers as well as strings¶ 'Variable declaration¶ Dim iNr As Variant¶ Do¶ Offset = Offset + 1¶ iNr = iNr & Mid(sString, Offset, 1)¶ Loop While IsNumeric(iNr)¶ ExtractNumber = Left(iNr, Len(iNr) - 1)¶ End Function¶ ' * * * * *¶ Sub MoveGraphicViaClipboard(shp As Word.Shape, _¶ PageNr As Long)¶ 'Variable declaration¶ Dim rngPage As Word.Range¶ Dim rngPageStart As Word.Range¶ Dim vw As Word.View¶ Dim lViewType As Long¶ Dim bWholePage As Boolean¶ 'Graphics can only be moved in the¶ 'Print Layout view. Save the user's¶ 'current view and restore it when done¶ Set vw = shp.Parent.ActiveWindow.View¶ lViewType = vw.Type¶ vw.Type = wdPrintView¶ 'Turn off hidden text as that will¶ 'falsify page numbers¶ vw.ShowHiddenText = False¶ If Val(Application.Version) >= 10 Then¶ 'Graphics will be positioned incorrectly¶ 'if the target range is not in view¶ 'In Word 2002 and 2003 be sure to¶ 'display the top and bottom margins!¶ bWholePage = vw.DisplayPageBoundaries¶ vw.DisplayPageBoundaries = True¶ End If¶ 'Put the graphic on the clipboard¶ shp.Select¶ Selection.Cut¶ 'Go to the required page¶ Selection.GoTo What:=wdGoToPage, _¶ Which:=wdGoToAbsolute, _¶ Count:=PageNr¶ Set rngPage = ActiveDocument.Bookmarks("\Page").Range¶ 'If the target page is the last page of the document¶ 'make sure to include the last paragraph mark¶ If rngPage.Information(wdActiveEndPageNumber) = _¶ rngPage.Information(wdNumberOfPagesInDocument) Then _¶ rngPage.MoveEnd wdParagraph, 1¶ Set rngPageStart = rngPage.Duplicate¶ Word Procedures Office VBA: Macros You Can Use Today page 173 Wrd 'Get the range for first para's starting point¶ rngPageStart.End = rngPage.Paragraphs(1).Range.Start¶ 'If the beginning of the first para¶ 'is on the preceding page, then the¶ 'graphic must be anchored to the second para¶ 'in order for it to appear on this page¶ If Val(rngPageStart.Information(wdActiveEndPageNumber)) _¶ < PageNr Then¶ rngPage.Paragraphs(2).Range.Paste¶ Else¶ rngPage.Paragraphs(1).Range.Paste¶ End If¶ vw.Type = lViewType¶ If Application.Version > 10 Then vw.DisplayPageBoundaries _¶ = bWholePage¶ End Sub¶ View the Appendix to learn how to store this procedure in a UserForm. Option explicit¶ ' * * * * *¶ Private Sub cmdCancel_Click()¶ Unload Me¶ End Sub¶ ‘ * * * * *¶ Private Sub cmdOK_Click()¶ ChangeGraphicName¶ Unload Me¶ End Sub¶ ' * * * * *¶ Private Sub UserForm_Activate()¶ 'Variable declaration¶ Dim sShapeName As String¶ sShapeName = GetGraphicName¶ If Len(sShapeName) = 0 Then¶ MsgBox "You haven't selected a graphic." & vbCr & vbCr & _¶ "Please select a graphic and try again.", _¶ vbOKOnly + vbCritical¶ Unload Me¶ Exit Sub¶ Else¶ Word Procedures page 174 Office VBA: Macros You Can Use Today Wrd Select Case Selection.ShapeRange(1).RelativeVerticalPosition¶ 'Positioned relative to the page¶ Case wdRelativeVerticalPositionPage, wdRelativeVerticalPositionMargin¶ If Left(sShapeName, 4) <> "Page" Then¶ sShapeName = "Page" & _¶ Selection.Information(wdActiveEndPageNumber) _¶ & "_" & sShapeName¶ End If¶ Case wdRelativeVerticalPositionLine, _¶ wdRelativeVerticalPositionParagraph¶ 'It's formatted to move with the text and¶ 'is therefore not linked with a specific page¶ Case Else¶ 'unknown Enum constant¶ End Select¶ txtGrafikName.Text = sShapeName¶ End If¶ End Sub¶ ' * * * * *¶ Sub ChangeGraphicName()¶ Selection.ShapeRange(1).Name = txtGrafikName.Text¶ End Sub¶ Function GetGraphicName() As String¶ If Selection.ShapeRange.Count > 0 Then¶ GetGraphicName = Selection.ShapeRange(1).Name¶ Else¶ GetGraphicName = vbNullString¶ End If¶ End Function¶ Copy the standard module to a document, to a template, or to Normal.dot. Transfer the user form 'frmNameGraphic' to the same project, either by using the Organizer or by dragging it in the Visual Basic Editor (VBE) to the template's project. To prepare a graphic so that the tool will recognize it: 1. First, format it with text wrapping (in the Layout tab of the Format dialog box). 2. Then, position it relative to the page (click Advanced in the Layout tab of the Format dialog box, choose the Picture Position tab, and deactivate Move with the text). Run the macro 'ShowGraphicName' and make sure the word "Page" plus the page number on which the graphic should appear are at the beginning of the graphic's name. Example: Page3 Picture of me Word Procedures Office VBA: Macros You Can Use Today page 175 Wrd When you have finished editing the text, run the 'MoveGraphicToPage' macro to reposition the graphics. Forms: Suppressing New Paragraphs in Form Fields This procedure disables the Enter key when the user is typing in form fields. It also demonstrates assigning a macro to a keyboard shortcut. Example file: W019 This set of macros dynamically changes the two keyboard assignments, depending on where the selection in the document is located. View the Appendix to learn how to store this procedure in a Standard module. Scenario: As a word processing program, Word is primarily concerned with text flow. The Textinput type of form field reflects this—by default, as much text as desired can be typed into the form. The form field wraps like any other text and displays its content on multiple lines. While this is appropriate for some applications, forms that mimic paper forms need to restrict the amount of space a form field can occupy. Word provides no direct functionality to accomplish the task; most often, the form fields are placed in table cells with an exact height and width setting. In some cases, it may be desirable to prevent the Enter key from creating a new paragraph in the form field, or the Shift+Enter key combination from generating a new line. However, if the form contains unprotected sections where the user can type and edit freely, these key combinations should be allowed to work normally in these regions. [...]... same time displaying a UserForm such as that shown below Double-click an entry, or select it and then click the Insert Field button in the form to insert the merge field into the document Figure 57 – User-Friendly Merge Field List page 200 Office VBA: Macros You Can Use Today Word Procedures Note: The following code should be placed in the UserForm module of the UserForm that will use it Option explicit¶... "DSN=Excel Files;DBQ=C:\Documents and Settings\User\My Documents\SalesData.xls;DriverId=790;MaxBufferSize=2048;PageTimeout =5; " _¶ SQLStatement:="SELECT * FROM `Sheet1$`", _¶ SQLStatement1:="", SubType:=wdMergeSubTypeOther¶ Office VBA: Macros You Can Use Today page 197 Wrd Word Procedures Below is the edited version Notice that all the information about passwords can be deleted; they are irrelevant when opening... the data source dynamically and displaying a user interface In this case, the AutoOpen macro could look like this: Sub AutoOpen()¶ LinkToSourceFile¶ DisplayMergeUserInterface¶ End Sub¶ Office VBA: Macros You Can Use Today page 199 Wrd Word Procedures M a i l M e r g e : C r e a t i n g a U s e r - F r i e n d l y L i s t o f F ie l d s This procedure lets you display the list of merge fields in a dialog... names used in any calculations¶ 'can be done.¶ nrFields = rng.FormFields.Count¶ ReDim aFieldNames(nrFields)¶ For counter = 1 To nrFields¶ aFieldNames(counter - 1) = rng.FormFields(counter).Name¶ Next counter¶ Office VBA: Macros You Can Use Today page 179 Wrd Word Procedures Wrd 'Add the increment to the field names, and to¶ 'the field names in any calculation¶ 'Run through from back to front because¶... cell, or to the contents from the selection point to the beginning or end of the cell page 182 Office VBA: Macros You Can Use Today Word Procedures Fo r m s : I n sertin g a New T a b l e Row Use this procedure to expand the number of rows provided in a table in a protected form Scenario: Forms are often used to create offers, invoices, and other types of repetitive data entry that are best organized... its row: Qty_1*Price_1, Qty_2*Price_2, etc The macro takes care not only of inserting the new rows, but also renames the fields and updates any calculation formulas Office VBA: Macros You Can Use Today page 183 Word Procedures Wrd Figure 55 – Auto-inserting Table Rows View the Appendix to learn how to store this procedure in a Standard module Option explicit¶ ' * * * * *¶ 'If the form has more than one... then used when protecting the form again 2 Create a toolbar button for this macro, and be sure to save the change in this template (Tools | Customize | Commands, the Macros category) 3 Finish setting up the form and then protect it 4 Set up the form and the basic table—a header row, if needed, and at least one "data row" containing form fields that will be repeated Office VBA: Macros You Can Use Today. .. 'varaible declaration¶ Dim doc As Word.Document¶ Dim rng As Word.Range¶ Dim totalRows As Long¶ Set rng = Selection.Range¶ If rng.Information(wdWithInTable) Then¶ Office VBA: Macros You Can Use Today page 189 Word Procedures Wrd 'Make sure user can' t accidentally delete¶ 'any rows at the end, such as a totals row¶ 'nor the last remaining "data row" in table¶ totalRows = rng.Tables(1).Rows.Count¶ If rng.Rows(1).Index... unprotect the form in order to delete the row If no password has been assigned, use a zero-length string ("") The macro runs from a toolbar that displays when a document is created using the template page 192 Office VBA: Macros You Can Use Today Word Procedures F o r m s : P la c i n g a P i c t u re i n a P r o t e c t e d F o r m Use this procedure to insert a picture into a protected section of a form... password has been assigned, use a zero-length string ("") bookmarkTarget The name of the bookmark marking the target position for the picture being inserted The macro runs from a toolbar that displays when a document is created using the template Set up the form Insert a bookmark at each location where the user should be able to insert a picture page 194 Office VBA: Macros You Can Use Today Word Procedures . Procedures page 168 Office VBA: Macros You Can Use Today Wrd rng.Select¶ 'Let the user add a caption¶ Dialogs(wdDialogInsertCaption).Show¶ End Sub¶ Making Changes You can change a number. to be incremented, and the formulas adjusted to use these names. Word Procedures page 184 Office VBA: Macros You Can Use Today Wrd Figure 55 – Auto-inserting Table Rows View the Appendix. graphic's name. Example: Page3 Picture of me Word Procedures Office VBA: Macros You Can Use Today page 1 75 Wrd When you have finished editing the text, run the 'MoveGraphicToPage'

Ngày đăng: 14/08/2014, 09:21

Từ khóa liên quan

Mục lục

  • Word Procedures

    • Inserting a Picture with Caption

      • Making Changes

        • Linking in a Picture

        • Inserting a Picture Without a Frame

        • Leaving off the Caption

        • Controlling the Picture Size

        • Setting Exact Height and Width

        • Adding Borders

        • Positioning the Frame

        • Wrapping Text Around the Frame

        • Changing the Path for Graphics Files

    • Associating a Picture with a Page

    • Forms: Suppressing New Paragraphs in Form Fields

    • Forms: Formatting Text Input in Form Fields

      • Changing Other Types of Formatting

    • Forms: Inserting a New Table Row

    • Forms: Deleting a Table Row

    • Forms: Placing a Picture in a Protected Form

    • Mail Merge: Using a Relative Path for Data Source

    • Mail Merge: Displaying the Mail Merge Interface

    • Mail Merge: Creating a User-Friendly List of Fields

    • Mail Merge: Making Placecards Using WordArt

    • Mail Merge: Creating a One-to-Many List

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan