Está en la página 1de 8

Que es un macro

Una macro es un conjunto de comandos o instrucciones enviados al programa,

que se ejecutan secuencialmente una tras otra.
De hecho macro es la abreviatura de macroinstruccin.


Automatizar una serie de pasos.

- Personalizar la barra de acceso rpido aadindole nuevas funcionalidades.

- Insertar texto o grficos que solemos utilizar frecuentemente. Por ejemplo, el

eslogn de la empresa, si lo tenemos en una macro nicamente lo escribimos
una vez y posteriormente lo insertamos mediante una macro.

Si disponemos de los conocimientos necesarios podemos hacer macros que

funcionen como si fueran comandos de Word y aadirlos a la barra de
herramientas o asociar cada macro a una combinacin de teclas especfica.
Esto lo veremos a lo largo de la unidad.


Private WithEvents app As Word.Application

Private doc As Word.Document

Private Sub AddText(text As String)

doc.Content.InsertAfter (text)
End Sub

Private Sub app_ProtectedViewWindowActivate(ByVal PvWindow As ProtectedViewWindow

AddText "ProtectedViewWindowActivate: " & PvWindow.Caption
End Sub

Private Sub app_ProtectedViewWindowBeforeClose(ByVal PvWindow As ProtectedViewWin

dow, ByVal CloseReason As Long, Cancel As Boolean)
' You can cancel the ProtectedViewWindowBeforeClose event.
Dim reason As String
reason = "None"

Select Case CloseReason

Case wdProtectedViewCloseEdit
reason = "Edit"
Case wdProtectedViewCloseForced
reason = "Forced"
Case wdProtectedViewCloseNormal
reason = "Normal"
End Select

Dim text As String

text = "ProtectedViewWindowBeforeClose: " & _
PvWindow.Caption & "(" & reason & ")"

AddText text
Cancel = (MsgBox(text, vbOKCancel, "Event") = vbCancel)
End Sub

Private Sub app_ProtectedViewWindowBeforeEdit(ByVal PvWindow As ProtectedViewWind

ow, Cancel As Boolean)
' You can cancel the ProtectedViewWindowBeforeEdit event.
Dim text As String
text = "ProtectedViewWindowBeforeEdit: " & PvWindow.Caption
AddText text
Cancel = (MsgBox(text, vbOKCancel, "Event") = vbCancel)
End Sub

Private Sub app_ProtectedViewWindowDeactivate(ByVal PvWindow As ProtectedViewWind

AddText "ProtectedViewWindowDeactivate: " & PvWindow.Caption
End Sub

Private Sub app_ProtectedViewWindowOpen(ByVal PvWindow As ProtectedViewWindow)

AddText "ProtectedViewWindowOpen: " & PvWindow.Caption
End Sub

Private Sub app_ProtectedViewWindowSize(ByVal PvWindow As ProtectedViewWindow)

AddText "ProtectedViewWindowSize: " & PvWindow.Caption
End Sub

Private Sub Document_Open()

Set doc = Word.ActiveDocument
Set app = Word.Application
End Sub


Sub TestGlowAndReflection()
With ActiveDocument.Range
.Font.Size = 24
.Font.Bold = True
.Font.Name = "Gabriola"

Dim i As Integer
' Note a few things:
' * The values of the StylisticSet enumerated values
' are powers of two. You can also use the wdStylisticSet01 and
' so on values to set individual stylistic sets.
' * Few fonts provide different stylistic sets. Gabriola provides just
' a few different sets, although you can still request all 20.
' * Fonts can have up to 20 stylistic sets, changing subtle features
' of the font.
For i = 1 To 20
.Paragraphs(i).Range.Font.StylisticSet = 2 ^ (i - 1)
Next i

.InsertBefore "Here is some text."
End With
With ActiveDocument.Range.Paragraphs(1).Range
With .Font
.Size = 24
.ColorIndex = wdRed
' Work with the Font.Glow property:
With .Glow
' Can also set the Color.RGB property:
.Color.ObjectThemeColor = wdThemeColorAccent1
.Radius = 10
.Transparency = 0.8
End With
With .Reflection
.Offset = 2.4
.Blur = 0.5
.Size = 100
.Transparency = 0.5
' You can also set the Type property, which
' includes settings for the preset Reflection
' types:
' .Type = msoReflectionType1
End With
End With
End With
End Sub


Sub CropDemo()
' Put your own image path in here. This image path
' should work for standard Windows 7 installations.
Const fileName As String = "C:\Windows\Web\Wallpaper\Landscapes\img10.jpg"

With ActiveDocument
Dim shp As Shape
Set shp = ActiveDocument.Shapes.AddPicture(fileName, msoFalse, msoTrue)

shp.Line.Visible = True

' Retrieve the dimensions of the shape:

Dim picWidth As Double
Dim picHeight As Double
picWidth = shp.Width
picHeight = shp.Height

With shp.PictureFormat.Crop
' Modify the picture itself, not its container:
' Shift the picture 10% to the right and down,
' and then make the picture 90% of its original size.
.PictureOffsetX = picWidth / 10
.PictureOffsetY = picHeight / 10
.PictureHeight = picHeight * 0.9
.PictureWidth = picWidth * 0.9
' Now modify the cropping by changing the shape
' of the container. Changing the shape alters
' the portion of the picture that you see:
.ShapeHeight = 100
.ShapeWidth = 100
.ShapeLeft = 100
.ShapeTop = 150
End With
End With
End Sub


Sub TestQuickStyles()
' Word 2010 adds the ability to apply a quick style set. Previously
' you could only save a quick style set.

' Apply one of the built-in style sets.

ActiveDocument.ApplyQuickStyleSet2 "Elegant"

' Modify the style set:

With ActiveDocument.Paragraphs(1)
.LineSpacing = 20
.LeftIndent = 20
End With
ActiveDocument.SaveAsQuickStyleSet "New Style"

' Load another style set:

ActiveDocument.ApplyQuickStyleSet2 "Word 2010"

' Re-apply your new style set:

ActiveDocument.ApplyQuickStyleSet2 "New Style"
End Sub


Sub DemoThemeAndQuickStyle()
' Modify this path for your own installation of Microsoft Office:
Const themeFolder As String = "C:\Program Files (x86)\Microsoft Office\Docume
nt Themes 14\"

' Single step through this code to see the changes as they occur.
' Look at the list of Quick Styles in the user interface
' for more quick style names:
ActiveDocument.ApplyQuickStyleSet "Distinctive"
ActiveDocument.ApplyQuickStyleSet "Elegant"
ActiveDocument.ApplyQuickStyleSet "Manuscript"

' These are just a few of the many available themes:

ActiveDocument.ApplyDocumentTheme themeFolder & "Verve.thmx"
ActiveDocument.ApplyDocumentTheme themeFolder & "Clarity.thmx"
ActiveDocument.ApplyDocumentTheme themeFolder & "Newsprint.thmx"
ActiveDocument.ApplyDocumentTheme themeFolder & "Solstice.thmx"
End Sub


ub TestCheckInWithVersion()
ActiveDocument.Content.InsertAfter "Here is a change!"

' The following code includes parameter names

' to make it clearer what's going on. All the parameters
' are optional, and you don't need to use named
' parameters.
ActiveDocument.CheckInWithVersion _
SaveChanges:=True, _
Comments:="I made some changes to demonstrate checking in.", _
MakePublic:=True, _
End Sub


Sub SelectionClearFormattingDemo()
' Apply character and paragraph formats.
' Press F8 to step into this the first time.
' Press Shift+F8 to step over subsequent lines of code:
ApplyFormattingAndSelect Sentences(3)

' Note that the sentence is now formatted.

' Remove the character direct formatting;

' Reapply the formatting:

ApplyFormattingAndSelect Sentences(3)

' Remove the character style formatting:


' Reapply the formatting:

ApplyFormattingAndSelect Sentences(3)

' Remove all character formatting (leaving paragraph formatting):


' Reapply the formatting:

ApplyFormattingAndSelect Sentences(3)

' Remove the paragraph direct formatting:


' Reapply the formatting:

ApplyFormattingAndSelect Sentences(3)

' Remove the paragraph style formatting:


' Reapply the formatting:

ApplyFormattingAndSelect Sentences(3)

' Remove all paragraph formatting (leaving character formatting):


End Sub

Sub ApplyFormattingAndSelect(rng As Range)

With rng
' Apply a paragraph and character style:
.Style = "Quote"

' Apply a character style:

.Style = "Subtle Reference"

' Apply direct formatting:

.Font.Bold = True
.Font.ColorIndex = wdBrightGreen
.ParagraphFormat.LineSpacing = 20
End With
End Sub


Sub DemoCompareDocuments()
' Save the current document, including this code.
Const path1 As String = "C:\Temp\Doc1.docm"
Const path2 As String = "C:\Temp\Doc2.docm"
Const path3 As String = "C:\Temp\Doc3.docm"

Dim doc1 As Document

Dim doc2 As Document
Dim doc3 As Document

' Save with macros enabled, because this code exists within
' the document you're saving. If the document didn't contain
' code, you would not need to specify the file format.
Set doc1 = ActiveDocument
doc1.SaveAs path1, wdFormatXMLDocumentMacroEnabled

' Make some changes to the current document:

Set doc2 = ActiveDocument
doc2.ApplyQuickStyleSet2 "Elegant"
ChangeTheDocument doc2

' Save the document as Doc2

doc2.SaveAs2 path2, wdFormatFlatXMLMacroEnabled

' Open the original document

Set doc1 = Documents.Open(path1)

Set doc3 = Application.CompareDocuments(doc1, doc2, _

Destination:=wdCompareDestinationNew, _
Granularity:=wdGranularityWordLevel, _
CompareFormatting:=True, _
CompareCaseChanges:=True, _

doc3.SaveAs2 path3, wdFormatFlatXMLMacroEnabled

End Sub

Private Sub ChangeTheDocument(doc As Document)

' Make some changes to the active document:
' Delete paragraph 3:

' Change a few words:

doc.Paragraphs(1).Range.Words(3).Case = wdUpperCase
doc.Paragraphs(2).Range.Words(6).Case = wdUpperCase
doc.Paragraphs(3).Range.Sentences(2).Case = wdUpperCase

' Delete a few words:


' Format a few words:

doc.Paragraphs(1).Range.Words(10).Bold = True
doc.Paragraphs(2).Range.Words(5).Italic = True
doc.Paragraphs(3).Range.Words(6).Underline = True
End Sub


Sub DemoSaveAsQuickStyleSet()
' Given the five paragraphs you added (by following the instructions),
' modify the color, font, and paragraph layout. Then save the whole
' thing as a new quick style.

Dim theme As OfficeTheme

Set theme = ActiveDocument.DocumentTheme

' Modify this path for your own installation of Microsoft Office:
Const themeFolder As String = "C:\Program Files (x86)\Microsoft Office\Docume
nt Themes 14\"

' Modify the name of the new template to meet your needs:
Const newTemplateName = "C:\temp\Demo1.dotx"

' Select one of the available theme color sets:

theme.ThemeColorScheme.Load themeFolder & "Theme Colors\Adjacency.xml"

' Select one of the available theme fonts:

theme.ThemeFontScheme.Load themeFolder & "Theme Fonts\Slipstream.xml"

' Save the settings as a new quick style set. This actually
' creates a new document template, which you can use for
' creating future documents.
ActiveDocument.SaveAsQuickStyleSet newTemplateName
' Verify that in the new document that this statement creates,
' the theme color and font correspond to the options you
' set when you created the quick set.
Documents.Add newTemplateName
End Sub


Sub RangeExportImportFragments()
' Word 2007 and later allows you to export ranges of text as a fragments.
' You can them reimport these fragments and use them in any document.

' Given the sample document with 5 paragraphs, try exporting a fragment,
' then modifying the format and reimporting the fragment to see the behavior.

' Change this path to match your own situation.

Const FRAGMENT_FILE As String = "C:\Temp\Fragment.docx"

Dim rng As Range

Set rng = Range(15, 150)
rng.Bold = True

rng.ExportFragment FRAGMENT_FILE, wdFormatDocumentDefault

' Take a moment and load the fragment file into Microsoft Word.
' It should load like any other document.

' Set formatting back to normal.

rng.Bold = False

' Although the second paramter indicates style behavior for the incoming
' fragment, it doesn't appear to make any different which option
' you choose. Both True and False give the same result. If False, the
' fragment should use the formatting from the original document, not the
' current document, but this doesn't appear to be the case. The ImportFragmen
' method uses the formatting from the source document, no matter how this
' parameter has been set:
Words(1).ImportFragment FRAGMENT_FILE, False
Words(100).ImportFragment FRAGMENT_FILE, True
End Sub

También podría gustarte