I Have some code which creates a header in Word from Excel:
wdApp.ActiveWindow.ActivePane.View.SeekView = 9
wdApp.Selection.TypeText ThisWorkbook.Worksheets("Rapport").Range("I4").Text
wdApp.ActiveWindow.ActivePane.View.SeekView = 0
Selection.ParagraphFormat.Alignment = wdAlignParagraphJustify
But an error occurs on the last row.
What I want to create with that row is that I want the header to be nice centerd.
This is how it is using the code. ( not what I want )
and this is how I want it to look
Option 1:
Try to change order of your instructions and, which is important, you need to add a special line break character at the and to get 'justification result'. Here is an example:
Selection.ParagraphFormat.Alignment = wdAlignParagraphJustify
Selection.TypeText "here is text from Excel" + Chr(11)
Option 2:
However, justification will not give you the result you presented as aligning words add extra spaced between each word. To get result which you have you need to add table which could go like this:
Dim tmpTBL As Table
Set tmpTBL = Selection.Tables.Add(Selection.Range, 1, 2)
With tmpTBL.Cell(1, 1).Range
.Text = "Date: " & Now
.ParagraphFormat.Alignment = wdAlignParagraphLeft
End With
With tmpTBL.Cell(1, 2).Range
.Text = "here is text from Excel"
.ParagraphFormat.Alignment = wdAlignParagraphRight
End With
The following screen shot presents both options.
Related
So, for my job, I have to create an open order report (OOR). I then create a word doc that highlights the "Key Points" of this report. So, when I run the Macro I've created for this report, I have the Key Points added to Sheet2 in the OOR spreadsheet.
I would then like these key points to be copied/pasted into MS Word in a bulleted list. So far, when running the macro, I can get a word doc opened and have it write out the title of the bulleted list, "Key points from file," but cannot get the bullet points added.
Please see the below code:
Selection.TypeText Text:="Key Points from the attached file: "
With Selection
.Font.Bold=True
.Font.Color= RGB(31,73,125)
End With
Selection.TypeParagraph
Selection.TypeText Text:=vbTab
With ListGalleries(wdBulletGallery).ListTemplates(1).ListLevels(1)
.NumberFormat = ChrW(61623)
.TrailingCharacter = wdTrailingTab
.NumberStyle = wdListNumberStyleBullet
.NumberPosition = InchesToPoints(0.25)
.Alignment = wdListLevelAlignLeft
.TextPosition = InchesToPoints(0.5)
.TabPosition = wdUndefined
.ResetOnHigher = 0
.StartAt = 1
End With
ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""
Selection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdBulletGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
wdWord10ListBehavior
Selection.TypeText Text:= Worksheet(“Sheet2”).Range(“C2”).Value
Selection.TypeParagraph
Selection.TypeText Text:= Worksheet(“Sheet2”).Range(“C3”).Value
Selection.TypeParagraph
I am needing to do this for cells C2:C10.
When writing macros the easiest way is to use the record macro button. Then see what it generates and use the VBA it generates.
Open Word, enable the developer ribbon (file | options | customise ribbon) and start recording a macro. Select some text and click the bullets button. Stop the macro and then you can see what the Word macro created in order to select the data and then format it.
I have an Excel document that uses VBA to generate 100+ quarterly reports from a central dataset. Pivot tables are copied from the Excel document and pasted into a Word document that serves as a template for the report.
One of the columns in the tables contains text that I would like to make into formatted hyperlinks to relevant pages related to the row data sources. I was unable to find a method for allowing the hyperlink to survive translation from the lookup table into the pivot table (the pivot table simple returns the display text, without the link).
My thought was to write a script that would search for the text string in the table and simply replace it with the formatted link. Unfortunately, I haven't been able to get this approach to work, despite trying several versions.
I'm fairly new to VBA, so may be missing something simple, but I'm stuck pretty good now. Here's what I've tried so far:
First Version
Tried to copy the formatted hyperlink from a designated cell in the Excel document and then Replace the search text with "^c"
ThisWorkbook.Worksheets("SheetA").Range("A1").Copy
With myDoc.Content.Find
.Execute findText:="target text string", ReplaceWith:="^c", Replace:=wdReplaceAll
End With
This version crashed with "Run-time error '6015': Method 'Execute' of object 'Find' failed" The specific error sometimes varies, but always triggers after replacing the first target text string with the copied cell. I thought that part of the issue might be that it was pasting the entire copied cell from Excel into the cell of the Word table (not just the hyperlink), but I couldn't find a way to paste just the link.
Second Version
Tried to directly code the search and link
Dim h, urlString, displayText as String
h = "target text string"
urlString = "desired address"
displayText = "hyperlink display text"
myDoc.Content.Select
With Selection.Find
.ClearFormatting
.Text = h
.Forward = True
.Wrap = wdFindContinue
End With
Do While Selection.Find.Execute
Selection.Text = "h"
ActiveDocument.Hyperlinks.Add Selection.Range, _
Address:=urlString, SubAddress:="", _
TextToDisplay:=displayText
Loop
This version gives me a "Run-time error '450': Wrong number of arguments or invalid property assignment" on the 'With Selection.Find' line.
I've tried a few other versions (and various combinations thereof) mostly trying to work from the appended links, but have gotten a similar lack of results. Hoping it's just something silly I've missed - appreciate any assistance!
Source 1
Source 2
Source 3
Source 4
The examples you looked at are either for vbscript or Word macros.
See here or here for Excel macro.
Sub update_links()
Const WORD_DOC = "C:\tmp\test.docx"
Const TARGET = "target text string"
Const URL = "desired address"
Const HYPERLINK = "hyperlink display text"
Dim apWord As Variant, wdDoc As Document, count As Integer
Set apWord = New Word.Application
apWord.Visible = True
Set wdDoc = apWord.Documents.Open(WORD_DOC)
wdDoc.Activate
count = 0
With wdDoc.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = True
.Text = TARGET
.Replacement.Text = ""
.Execute
End With
Do While .Find.Found = True
With .Find
apWord.ActiveDocument.Hyperlinks.Add _
Anchor:=.Parent, Address:=URL, _
TextToDisplay:=HYPERLINK
count = count + 1
End With
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
wdDoc.SaveAs "c:\tmp\test_updated.docx"
wdDoc.Close
apWord.Quit
Set apWord = Nothing
MsgBox count & " links added to " & WORD_DOC, vbInformation
End Sub
I have already reviewed a couple of similar posts here, here, here (including referenced link) and here in careful detail, and not found anything that helped.
My script starts in an Excel construction estimate and outputs a proposal draft in Word. The general structure of the program is in three parts:
It pulls the data from the active worksheet (lines 1-226), then
It queries the user for some final needed bits of info via a userform (lines 227-265), then
It opens a letterhead template in Word and dumps everything into it (lines 266-763).
The first time I run the script from the Excel estimate, it executes flawlessly, all the way through to saving the Word document. But if I close that generated Word document and click the "Draft proposal" button again, it gets to a very specific line, not far into the Word portion of the program, and gives me an error, every time. That error is,
"Run-time error '462': The remote server machine does not exist or is unavailable."
Here is the script, starting at the beginning of the Word portion. It breaks at the line where we give our "$TBD" price, right-justified, at the end of trailing dots.
I used a macro to generate this little block of code. I have attempted to fix this bug by simplifying the code here. I used to have unnecessary lines wDoc.DefaultTabStop = InchesToPoints(0.5) and sel.ParagraphFormat.TabStops.ClearAll and it used to break at those lines, but I deleted both of them, and the program still breaks right at the same spot.
'open the Word document with the appropriate template, bind worksheet & doc together,
'activate the window (bring to front), and move cursor to the end of the document
Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
Set wDoc = wApp.Documents.Add(Template:="C:\Users\" & MyUserName & "\"
'The rest of the filepath is included here, but I'm omitting it for security purposes, ending in "Letterhead.dotm")
wApp.Visible = True
wApp.Activate
Dim sel As Word.Selection
Set sel = wDoc.Application.Selection
sel.EndKey (wdStory)
'create date and address block
sel.InsertDateTime DateTimeFormat:="MMMM dd, yyyy", InsertAsField:=False
sel.TypeParagraph
sel.TypeParagraph
sel.TypeText Text:=ContactName
sel.TypeText Text:=Chr(11)
sel.Font.Bold = wdToggle
sel.TypeText Text:=GCName
sel.TypeParagraph
sel.TypeParagraph
sel.TypeText "Reference: " & vbTab
sel.TypeText Text:=JobName
sel.Font.Bold = wdToggle
sel.TypeParagraph
sel.TypeParagraph
'create the introductory matter to the proposal
sel.TypeText "We are pleased to offer our proposal for the electrical portion of work " & _
"at " & JobAddress & ". Work is based upon " & ArchitectName & " " & PlanType & _
" drawings, dated " & PlansDated & "."
sel.TypeParagraph
sel.TypeParagraph
'make the line of dots before TBD, copy-pasting from a macro
sel.ParagraphFormat.TabStops.Add Position:=InchesToPoints(6.67), Alignment:=wdAlignTabRight, _
Leader:=wdTabLeaderDots 'This is the two-line statement where it breaks.
Oddly, if I delete the offending statement, it gets a little further but then breaks at another random line a little ways down, the ".NumberPosition" property definition within the myNLT With block:
'write the price line, and then erase the single-use tab stop we just set up
sel.Font.Bold = wdToggle
sel.TypeText "We will perform this work for" & vbTab & "$TBD"
sel.Font.Bold = wdToggle
sel.TypeParagraph
sel.TypeParagraph
sel.ParagraphFormat.TabStops.ClearAll
'introduce the itemized SOW
sel.Font.Bold = wdToggle
sel.Font.Underline = wdUnderlineSingle
sel.TypeText "Scope of work to include the following:"
sel.TypeParagraph
sel.Font.Underline = wdUnderlineNone
sel.Font.Bold = wdToggle
'set up itemized list, copy-pasting from a macro, list starts at 1
'establish myNLT as the numbered list template
Dim myNLT As ListTemplate
Set myNLT = wApp.ListGalleries(wdNumberGallery).ListTemplates(1)
With myNLT.ListLevels(1)
.NumberFormat = "%1."
.TrailingCharacter = wdTrailingTab
.NumberStyle = wdListNumberStyleArabic
.NumberPosition = InchesToPoints(0.25) 'If I delete the line indicated
'in the previous block of code, then this is the next place it breaks.
.Alignment = wdListLevelAlignLeft
.TextPosition = InchesToPoints(0.5)
.ResetOnHigher = 0
.StartAt = 1
.LinkedStyle = ""
End With
I have tried On Error Resume Next and I've tried even adding, as "Next," an Application.Wait for two seconds followed by a repetition of the TabStops.Add, but this does nothing but mess up my formatting.
I also tried changing sel.ParagraphFormat.Tabstops.Add to Word.Selection.ParagraphFormat.TabStops.Add - also didn't work.
Following a suggestion in comments also did not work: If I remove everything after .Add, I get
Compile error: Argument not optional.
If I then add back in the first argument, Position:=InchesToPoints(6.67) and leave off Alignment and Leader, then the error comes back.
I am currently working on a project using VBA and it isn't a language I am conformtable with.
I am trying to take all of my data in the spreadsheets and paste them to a word template using a .Find function that finds the appropriate tags.
It works until it gets to placing the final table at the end of the document after the Search finds the string its looking for. This is due to the table being dynamic and therefore will always have a different number of rows so it can't have a predefined table.
If Len(Trim(.Cells(1, lCol))) <> 0 Then
sSearch = .Cells(1, lCol)
sSearch = "<<" & Trim(sSearch) & ">>"
sTemp = .Cells(lRow, lCol)
With oDocRange.Find
.ClearFormatting
.Text = sSearch
.Replacement.ClearFormatting
' check - how to figure if string type?
' // If the cell text is > 255 then we get an error.
' // Calculate how many 'Chunks' of 250 are required to accomodate the long string.
' // If more than 1 chunk of text then we replace the original template
' // parameter with the first chunk and then insert additional parameters {2}, {3} etc
' // into the template and replace those with the additional chunks
chunks = Round(Len(sTemp) / 250, 0)
sTemp = Replace(sTemp, vbNewLine, vbCr)
sTemp = Replace(sTemp, Chr(10), vbCr)
If sSearch = "<<Checklist>>" Then
rng2.Copy
.Execute
Set wrdTable = oDoc.Tables.Add(Range:=oDocRange, NumRows:=1, numColumns:=4)
'With wrdTable
'Selection.PasteAndFormat
'.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, Placement:=wdInLine, DisplayAsIcon:=False
'End With
'.Execute FindText:="<<Checklist>>", ReplaceWith:=Selection, Format:=True, Replace:=wdReplaceAll
End If
If Len(sTemp) Mod 250 > 0 Then chunks = chunks + 1
If chunks = 1 Then
.Replacement.Text = sTemp
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
Else
.Execute FindText:=sSearch, ReplaceWith:="{1}", Replace:=wdReplaceAll
For i = 1 To chunks
chunk = Mid(sTemp, ((i - 1) * 250) + 1, 250)
If i < chunks Then chunk = chunk & "{" & (i + 1) & "}"
.Execute FindText:="{" & i & "}", ReplaceWith:=chunk, Replace:=wdReplaceAll
Next i
End If 'If chunks is > 0
End With ' the oDocRange.Find
End If 'If the column value isn't blank
sSearch is what words the program is looking through the word document for. And I want it to find Checklist, and replace it with the table I have set as rng2.
In the If statement I have a bunch of failed attempts but it always comes back to a "Type Mismatch" Error.
Any help is greatly appreciated and I would be happy to give any more information. Thank you!
I believe the Error is because of the Excel.VBA script is getting used for Word.VBA script and visa versa.
The script below is a simple Excel.VBA script which opens a specific Word Document and then searches for sSearch and then copies a range of Cells from Excel.
What I found was that I needed to reference each Application when I wanted to operate that Application. Example for Word I needed to use Word.Selection and for Excel Excel.ActiveSheet.Range("A1:F13:)
Sub SomeSubRoutine()
Dim WordProgram As Object
Dim WordFile As Object
WordFilePath = "Some File Path"
'Starting Word
Set WordProgram = CreateObject("Word.Application")
'Allowing it to be visible or not visible (For Developing its always good to have it visible
WordProgram.Application.Visible = True
'Opening the desired Word File
Set WordFile = WordProgram.Documents.Open(Filename:=WordFilePath)
'Here you can allocate your sSearch String
sSearch = "<<Checklist>>"
With Word.Selection.Find
.ClearFormatting
.Text = "<<Checklist>>" 'sSearch
' .Execute
Do While .Execute
If .Found = True Then
Set EventData = Excel.ActiveSheet.Range("A1:F13")
'Copying Event Log from the opened Excel File
EventData.Copy
With Word.Selection
'Pasting Event Log into Word Doc
.PasteAndFormat Type:=wdFormatOriginalFormatting
'Selecting the Table
.Tables(1).Select
'Horizontal Centering Text in the Table Rows
.ParagraphFormat.Alignment = wdAlignParagraphCenter
'Center Table to Page Center
.Tables(1).Rows.Alignment = wdAlignRowCenter
'Vertical Centering of Text in the Table Row
.Cells.VerticalAlignment = wdCellAlignVerticalCenter
'Moving out of the Table to continue search
.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
End With ' Ending "Word.Selection"
Else
'If nothing found then some other script can go here
End If 'Ending "If .Found"
Loop
End With ' Ending "Word.Selection.Find"
'Quiting the Word Application
WordProgram.Quit
'clean up Objects for next use
Set WordProgram = Nothing
Set WordFile = Nothing
End Sub
Just check your referencing to each application for all your search.
I have numerous WORD documents that have several Content Controls in them. I am using an Excel file to update the WORD docs. When I make an update, I need to insert a footnote describing the change. I can update the contents of the Content Control just fine, but I am having problems inserting the footnote. Here's my code:
Set cc = oRange.ContentControls(intCounter)
strOriginalDate = cc.Range.Text
If wrdDoc.ProtectionType <> wdNoProtection Then
wrdDoc.Unprotect strSheetPassword
End If
If wrdDoc.FormsDesign = False Then
wrdDoc.ToggleFormsDesign
End If
cc.Range.Text = strCOD
'
' Insert the footnote
'
oRange = wrdDoc.Range(cc.Range.End, cc.Range.End)
oRange.Select
Selection.MoveRight Units:=wdCharacter, Count:=1
Selection.TypeText Text:=" "
With Selection
With .FootnoteOptions
.Location = wdBottomOfPage
.NumberingRule = wdRestartContinuous
.StartingNumber = 1
.NumberStyle = wdNoteNumberStyleArabic
.LayoutColumns = 0
End With
.Footnotes.Add Range:=cc.Range, Text:="Case Opening Date changed from " & _
strOriginalDate & " to " & strCOD & " on " & Date, Reference:=""
End If
End With
wrdDoc.ToggleFormsDesign
wrdDoc.Protect Type:=wdAllowOnlyFormFields, Password:=strSheetPassword
wrdDoc.Save
When I get down to the line Selection.MoveRight Units:=wdCharacter, Count:=1, I get an error that says Object doesn't support this property or method. In essence, I'm trying to move to the end of the control, then on the next step, I'm trying to move beyond/outside the control.
When I comment out that line and the line that follows it, I end up trying to insert the footnote into the content control. That fails on the With .FootnoteOptions line, possibly because the content control I'm using is a date picker.
You are correct that you can't add a footnote inside of a Content Control. The solution is exactly what you are trying to do - put it in the document after. The problem is that you are trying to add it using the Selection object.
Since you already have a Range within the context of the Document (oRange), just work with it directly:
'
' Insert the footnote
'
'Move the oRange to an "insertion point" after the control.
oRange.Start = cc.Range.End + 1
'Collapse it.
oRange.End = oRange.Start
'Add your space.
oRange.Text = " "
With oRange.FootnoteOptions
.Location = wdBottomOfPage
.NumberingRule = wdRestartContinuous
.StartingNumber = 1
.NumberStyle = wdNoteNumberStyleArabic
.LayoutColumns = 0
End With
oRange.Footnotes.Add Range:=oRange, Text:="Case Opening Date changed from " & _
strOriginalDate & " to " & strCOD & " on " & Date
There's really no reason to be mucking around with the Selection - it's just a glorified Range with the added benefit of doing all the annoying things that Word does "for your benefit" (like grabbing the trailing space) while you're highlighting with the mouse.
I'll also note that you can omit the Reference:="" - it gets set to an empty string by default. You also have a floating End If inside your With block.