In vba word. I have a .dotm template file with content blocks. The path in the content blocks works if the .dotm file is in that path.
Application.Templates( _
"**L:\06. MODELOS DE DOCUMENTOS\01 ATESTADOS\ACCIDENTES DE CIRCULACIÓN\BAEI\Informe Tecnico\BAEI - INFORME TÉCNICO.dotm**"). _
BuildingBlockEntries("INICIO Y EXPOSICION DE HECHOS").Insert Where:=Selection.Range, RichText _
:=True
If someone takes the .dotm template file to another path, the content blocks no longer work.
Is it possible to create a macro that asks the user where to save the .dotm template file and substitutes the new path in the code?
Put the building block and the macro in the same template.
Then you can use ThisDocument.Fullname as the location in your code for the building block. This and other possibilities are explored in my page on building blocks.
This question is cross-posted. Much more extensive exploration of the possibilities and problems in the other forum. Please see A message to forum cross-posters.
Related
Consider VBA for PowerPoint -
Is this a valid Presentations function call?
Presentations(".\directory\ppname.ppt")
Note that this will be called from within a PowerPoint presentation VBA, to open another one in a sub-directory.
The Microsoft Presentations examples (and most others) are not specific about the filename forms accepted, e.g. those using the ".", "..", "\" directives recognized in DOS scripts.
This seems to work with Powerpoint 2007.
As described in the comment, it takes a block of text (the TextRange), the starting position and length of file reference, also a LinkAddr. LinkAddr is essentially a DOS-style file reference, like "..\folder\ppfile.ppt".
The intention here is to launch another PowerPoint tool by invoking its show.ppt or show.ppsm file name. The file name can refer to some other directory using MSDOS file name stuff. I don't know whether it can span different machine platforms, but it seems to work within one Windows 10 system.
My difficulty in getting this to work was some full-path links to images, e.g. something like C:\blah\blah\image.jpg, in the Visual Basic code. PowerPoint didn't like these, instead asked about enabling macros, and just hung up when one of my file links were to be executed. By getting rid of the "macro" complaints, this suddenly started working.
Or maybe some bugs have been fixed in recent repairs to my 2007 PowerPoint tools??
Go figure...
Sub InsertLink(ByRef Trange As TextRange, fpos As Long, msglen As Long, LinkAddr As String)
' Insert an HTML link into the selected TextFrame.
' get the character range
Dim Hrange As TextRange
Set Hrange = Trange.Characters(Start:=fpos, length:=msglen)
' make it an HTML link
With Hrange.ActionSettings(ppMouseClick)
.Action = ppActionHyperlink
.Hyperlink.Address = LinkAddr
End With
End Sub
We have .htm files we would like to edit with an Excel macro.
Here's what I have so far, which is an attempt to open the file, replace some placeholders inside the HTML body, and then save the file as an HTML file:
Sub SaveCustomerCountHTML()
Dim customerCountHTML As HTMLDocument
Dim customerCount As String
Dim customerPercentage As String
Dim strHTML As String
Set customerCountHTML = CreateObject("O:\00.Department Documents\06.Status Board Updates\Daily Sales\Templates\CUSTOMER COUNT.htm")
strHTML = customerCountHTML.HTMLbody
customerCount = "55"
customerPercentage = "2"
strHTML = Replace(customerCountHTML.HTMLbody, "%CUSTOMERCOUNT%", customerCount)
strHTML = Replace(customerCountHTML.HTMLbody, "%CUSTOMERPERCENTAGE%", customerPercentage)
customerCountHTML.SaveAs Filename:= _
"O:\00.Department Documents\06.Status Board Updates\Daily Sales\Templates\CUSTOMER COUNT2.htm", _
FileFormat:=xlHtml, _
CreateBackup:=False
End Sub
We definitely don't want to open the file in Internet Explorer - we just want to edit the placeholders in the body and re-save to another folder it without seeing what it's doing.
I receive an error message "ActiveX component can't create object" on the "Set customerCountHTML" line. We were also getting an "Object doesn't support this property or method" error for the HTMLBody lines, even though we included the Microsoft HTML Object Library in our references.
Again, the intention/attempt is to simply open the HTML file as an object, replace text in that file, and save the file. All of this without needing to see anything opening or closing. Most of the answers online include Internet Explorer or Outlook in some way, and we simply want to edit the file.
As #Comintern suggests, HTML files are nothing more than text files. You can open them and work on them as text files, and you can save them as text files, but with an .htm/html extension.
However, working with text files doesn't give you any contextual information, so you can't easily distinguish a table tag, the use of table in css or javascript or attributes, or in actual content.
If you know the exact text you want to replace is unique and reliably found without any False Positives, then replacing the text is good enough. But if you need to be able to find and replace specific parts of the HTML that might be ambiguous, then it might be worth ensuring that the file is XHTML compliant, and opening the file with the MSXML type library. You can then work with the file as an XML Document including a node-tree and all of the MSXML features for finding nodes.
I am attempting to do this from Access 2010 using Word 2010. I have a WordDoc object and cannot find a way to embed a file.
I tried starting from nothing using a bookmark:
bmFile.Range.InsertFile "C:\Users\Me\Desktop\TestFile.xlsx"
and that trew an error about the File being corrupted.
I tried editing an existing embeded file using WordDoc.InlineShapes(1) but no properties were changable or relevant.
Any ideas would be greatly appreciated.
Thanks
theWordDocObject.InlineShapes.AddOLEObject _
FileName:="pathtofile", _
LinkToFile:=False, DisplayAsIcon:=False
(works at least with Excel files)
From an existing file (as per your example) you should be able to do this
bmFile.Range.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.12", _
FileName:="C:\Users\Me\Desktop\TestFile.xlsx", _
LinkToFile:=False, _
DisplayAsIcon:=False
It's actually nastier to insert an object without using a file. You can do it by setting the FileName parameter to "", but then the OLE server will be started and display its UI (which doesn't happen when you embed from a file).
As for modifying anything in the embedded object, it isn't particularly straightforward because the object's UI tends to get in the way, but the starting point is the OLEFormat member of the Shape (or InlineShape). Difficult to find because "OLEFormat" is not a particularly informative name.
I have a VBA script used to process Word documents. The first thing the program does is to create an index of the documents in a defined set of folders. It then goes through the list processing each of the indexed documents.
The problem I am having is that it will sometimes decide that a particular document cannot be found, even though it previously indexed the document and a quick spot check shows the document to be in the correct place.
Can anyone shed some light on why VBA should display this behaviour?
The script is using the Dir$ function to index the files, and the Documents.Open function to open each word document for processing.
Sample code:
ChangeFileOpenDirectory (folderName)
inputFileName = Dir$(folderName & "*.doc")
Do While inputFileName <> ""
... call various functions here ...
inputFileName = Dir$
Loop
One of the functions called in the block has the following line:
Set currentDoc = Documents.Open(fileName:=docFileName, AddToRecentFiles:=False, Visible:=False)
This is the point at which the code is failing.
One of the most annoying things I have found is that recent files links are returned as the files themselves with Dir. You can use the FileSystemObject to check the file type.
I copy/paste your code and it works correctly.
However, it leaves all the files open (and hidden), and when you run it in another directory, additional files are opened and added to the open projects (take a look in the VBA editor).
My only guess is that after a while you're hitting the maximum allowable number of open files.
Try adding
currentdoc.Close
just before
inputFileName = Dir$
A few reasons, some duplicated from other answers:
If the path+ filename is long enough ... (you already answered in a comment)
If you are writing new files to same directory, Dir$ may get corrupted (happened to me)
If you have filenames with non-std chars (ex. "#")
Files locked by other processes
Files deleted while the macro is running
You may also try this code ...
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(file) Then ....
First enable the Microsoft Scripting reference in the VBE
I'm using Microsoft Office 2003 and creating a bunch of template documents to standardize some tasks. I asked this on Superuser.com and got no response so I'm thinking it's too program-y and hoping I'll have better luck here.
I need to automate a work flow that uses a bunch of Office (mostly Word) templates. What I want is to have "My Template Foo.dot" and "My Template Bar.dot", etc. in the "My Foo Bar Stuff" on a shared drive and have users double click on a template to create a new Foo or Bar.
What's I'd really like is for the user to double-click on the Foo template and be prompted for a couple of items related to their task (e.g., a project number) and have a script in the template change the name that Save will default to something like "Foo for Project 1234.doc".
I asked on Google Groups and got an answer that worked....for a while. Then my AutoNew macro stopped kicking in when I created a new document by double-clicking on the template. I have no idea why or how to debug it.
In Class Modules/This Application, I have:
Sub AutoNew()
Dim Project As String
Project = InputBox("Enter the Project Number")
ActiveDocument.SaveAs "Project " & Project & " Notes.doc"
End Sub
In Microsoft Word Objects/ThisDocument, I have:
Private Sub Document_New()
End Sub
I really have no idea why or where that came from.
In Tools/Macro Security... I have Security Level set to "Low".
I'm a software engineering with 25+ years of experience but a complete Office automation noob. Specific solutions and pointers to "this is how to automate Word" FAQs are welcome. Thanks.
Update: If I create a new template (New..., Blank Document, Save As "My New Template.dot"), and insert the AutoNew() macro, it works. So what's inhibiting it from working on my existing template?
Update 2: Removing the module and function from my old template and adding it back works, too.
You can attach a template to a saved document in ordre to access the macros contained in the template in question.
You can do this with the AttachedTemplate property of a Document object (i.e. ActiveDocument).
Please note that I did not try this myself.
Sub AutoNew()
Dim Project As String
Project = InputBox("Enter the Project Number")
ActiveDocument.SaveAs "Project " & Project & " Notes.doc"
ActiveDocument.AttachedTemplate = "\\path\to\templates\My Template Foo.dot"
End Sub
See MSDN - Word 2003 VBA Language Reference - AttachedTemplate Property
Hope that helps.
Check if the macro is still contained in your template. This sounds stupid but it happended to me, too, in Word 2003 under the following circumstances:
Create a template containing macro,
everything fine
Create a new document file based on
the macro, macro kicks in
Notice I could improve the template
here and there a bit, I do it in the
file created in 2) and SaveAs .DOT
Macro in .DOT GONE!
Why? Because the code stored in the .DOT doesn't go over to the doc file.