Word VBA macro errors opening files when run on some computers but not others? - vba

This has been a thorn in my side for months. It happens off and on for a small (but growing) number of users at my company, but not others running the same exact Word VBA Macro. The users get "5097:Word encountered an issue" or "4605: Command failed" runtime errors on lines of the code that open word or txt files. All are running the same build of windows and have the same permissions (according to the tech team.) The files are on a shared network drive.
Public Function readData(datafile As String) As String
'datafile = "\\network\unc\path\folder\folder\data.txt"
'I have confirmed this passes to the function correctly.
Dim db As Document
'Before it is suggested, I've tried early-binding, late-binding, and
'diming as Variant, Object, etc. to no effect
'Errors on this line
Set db = Documents.OpenNoRepairDialog(fileName:=datafile, ConfirmConversions:=False, _
ReadOnly:=True, Visible:=False)
'I have tried Documents.Open to no avail, in addition to toggling all of the parameters to
'or removing parameters see if I would get a different result.
'I have tried declaring the Word.Application and Application objects and prepending that
'to the function. Nadda. I also tried just the function, without setting as an object. No dice.
'---rest of code---'
End Function
I've used Debug.Print to check the file path was passed to the function correctly--it is. Also this issue does not have to do with the file being a txt file. If I comment out this function in the main sub, I get the same error on the next function that attempts to open a word doc.
Again, this exact macro runs flawlessly on some workstations.
Here's the real kicker:
The users are all able to navigate to the file paths the macro is trying to open in File Explorer without problem. When I run the "Documents.Open(datafile)" or "Dir(datafile)" functions in the immediate window they work perfectly, no issue. What gives?

Related

Powerpoint VBA Presentations File names

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

VBA Dynamic Save As, Microsoft Project to Excel

I am trying to create a macro that will export a Microsoft Project file into an excel file. Through the use of macro recording I have got a line of code that accomplishes this using the export wizard, but I want the file path and file name to be dynamic so I can use this macro on different projects. I have been searching many other threads and the Microsoft website with no luck. Is this possible?
Here is what I have:
sub formatAndSave ()
FileSaveAs Name:="C:\Users\XXXXXX\SharePoint\Projects\ProjectType\HxH\myProject.xlsx",_
FormatID:="MSProject.ACE", map:="myMap"
end sub
One idea I tried was:
Active.Workbook.SaveAs FileName:=Title
Any help would be very much appreciated!
For the sake of simplicity, let's assume for all answers below your project is located at c:\projects\myProj.mpp
I think you're after the string replace function. Something like:
Dim excelFilePath As String
excelFilePath = Replace(ActiveProject.FullName, ".mpp", ".xlsx")
Debug.Print excelFilePath
'the output would be c:\projects\myProj.xlsx
If you're unfamiliar with string manipulation in VB/VBA, just search the web for "VBA string manipulation". Microsoft has a decent article here: https://msdn.microsoft.com/en-us/library/aa903372(v=vs.71).aspx
A few other things that may be handy for you are these variables:
ActiveProject.FullName 'shows full path & name, so you'd get "c:\projects\myProj.mpp"
ActiveProject.Path 'shows just the path, so you'd get "c:\projects\"
ActiveProject.Name 'shows just the file name, so you'd get "myProj.mpp"
Finally, one caveat I've seen is that the ActiveProject.FullName and ActiveProject.Name variables may or may not provide the file extension depending on your local windows environment settings. I've observed that if Windows Explorer is configured to hide file extensions, then these variables also withhold the extension; if Explorer is configured to show them, then they are provided in the variables. Make sure your code is robust to both cases, or make sure you have control over the environment where you code will run.

How do I fix Error 432 when loading a form in Word VBA?

I have a Word .dot file which works in older versions of Word but fails with error 432 when run in Word 2013.
When I debug the code I have the line:
Load customerForm
And VBA shows the error:
Run-time error '432': File name or class name not found during Automation operation
The project "pennyscode" includes "Module1" which contains the function being debugged, "ThisDocument" and a form called "customerForm".
I have tried changing the name to "pennyscode.customerForm" but this doesn't make any difference.
This code is being called from a Sub function which is called from Document_New().
Updates
I can place a breakpoint on the Load customerForm line and demonstrate that it is the line that is causing the problem. If at this point I mouse over the word "customerForm" VBA comes up with
customerForm = <Object variable or With block variable not set>
If I delete/skip the Load line then the next line is customerForm.Show and that produces the same error.
If I just open the .dotm file and then use Alt-F11 to open VBA, I can look at the code for selectCustomer, list properties/methods and customerForm appears in the list.
Additional Note
I believe that within the Load function it must be calling GetObject and it is this that is failing. It is as if VBA can't find the customerForm object even though it appears in the project.
I've posted the full code of the function being called from Document_New below.
Sub selectCustomer()
Dim Doc As Document
Set Doc = Application.ActiveDocument
If Doc.CustomDocumentProperties.Item("Customer") = "Nothing" Then
Load customerForm
customerForm.Show
Unload customerForm
Doc.Fields.Update
a$ = Doc.CustomDocumentProperties.Item("InvoiceNumber")
a$ = customerForm.pathBox.Value + "\" + a$
Doc.SaveAs (a$)
End If
End Sub
I've also posted the full .dotm (Excel 2013) and .dot (previous excel) and some sample data (.xls) here:
Dropbox/Public/Invoice 2015-16.dotm
Dropbox/Public/Invoice 2015-16.dot
Dropbox/Public/data.xls
Update
I've not had much luck making progress on this question. Can anyone suggest an approach to investigating this? Or how I might improve the information on the question?
I finally managed to fix this, and I have a few learnings.
Firstly the debugger shows the error as occurring on the Load customerForm line, but this is actually not the case.
The customerForm has an _Initialize function which loads data into it before it is displayed. This function was failing with but the debugger stops on the wrong place.
I was able to debug this more effectively by putting a breakpoint on the start of the _Initialize sub and then stepping through the code.
Once I had discovered this I realized that the code was failing to find the XLSX file due to a wrong path, thus causing the run-time error.
Once I'd fixed up all the paths, I then hit a second error: runtime error '9' which is a subscript problem. This also reported on the Load customerForm line and was also due to a problem with the _Initialize function.
This was the true source of the problem, and demonstrated a functional change between Office 2013 and previous versions of Office.
My code was opening an XLSX file and attempting to read data from it:
Dim myXL As Object
Dim myWS As Object
Set myXL = GetObject("C:\Test\data.xlsx")
myXL.Application.Visible = True
myXL.Parent.Windows(1).Visible = True
Set myWS = myXL.Application.Worksheets("Customers")
The run-time error 9 was due to the index of the Windows property, as their were no windows. In previous versions of Office, there was a single window, with 2013 the array is empty.
After much messing about I tried adding this line:
myXL.Activate
before accessing the Windows() array. Once that was executed Windows(1) existed and the code worked as before.
Hope this can help someone else struggling with similar problems.

Publish an excel worksheet as an HTML file using a command button

So I have tons of data in my workbook that I need to pass on to my users in a way that allows them to interact with the workbook..., but also limits what they can actually do. So I have made it so they can access certain pages to Add needed data, then I've given access to a menu page so they can run a report.
This report I have found is best if it's an html page.
To that end, I have tried several different ways, save as...and publish. I like the publish version, but I can not for the life of me get this working. All the samples I see, appear to be the same. Here is the line of code in question:
ActiveWorkbook.PublishObjects.Add(xlSourceSheet, ActiveWorkbook.Path & ".htm, "Sheet1", "", xlHtmlStatic, "", "Report Title").Publish True
Every time I get a run time error '1004':
Method 'Publish' of object 'PublishObject' failed
I have the above line of code in a sub, am I missing something? Do I need to set up the publish differently? Thanks for any ideas.
I have had a similar mysterious problem that sometimes it (.Publish) works and sometimes it doesn't, when I try publish.
However, I think the problem might be, in cases when it doesn't work right off the bat, to first save the relevant region as a webpage so that it exists already on the server. After that region has been saved at least once (manually or else maybe with .SaveAs .. see below), then the publish might work.
Here is an example of how I get this to work more consistently, something to convey the structure that works for me:
wkb=ActiveWorkbook.Name 'save wb for later access
url="http://a.com/b.htm" 'save to Internet
sheetname="c"
Sheets(sheetname).Range("d1:e2").Select 'activating sheet may be necessary
On Error Resume Next 'anticipate error to handle it
'Now comes the publish line the first time... which may work.. or not
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'may fail to create page on website if page didn't already exist
theerr=Err.Number
On Error GoTo 0 'back to default error handling (none)
If theerr <> 0 Then 'if here perhaps because page nonexistent
'msgbox "maybe add warning here [FYI]"
Sheets("dummysheetwithlittleornodata").Copy 'will create workbook
On Error Resume Next
ActiveWorkbook.SaveAs url 'may fail to create webpage first time
ActiveWorkbook.saveAs url 'twice needed for some reason sometimes. [works for me]
On Error GoTo 0
'with fresh dummy html page created, now publish should hopefully work.. let's try again
ActiveWorkbook.Close savechanges:=False 'clean up and avoid popup
Workbooks(wkb).Activate 'get back to correct wkb
Sheets(sheetname).Range("d1:e2").Select
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'hopefully if failed first time, now it succeeded ! good luck.
End If
The above code structure has allowed me to solve several publish problems I was having. All the techniques together have been enough so far to allow me to save a range from a sheet as a webpage (to server I have write access to) without having to do anything manually (like a manual save or even click on popup). Good Luck.
[The different non-obvious techniques include activating a range before trying a range publish, using the error handling approach and anticipating failure at certain points, the 2x saveas to compensate for mysterious inconsistent failures when using one saveas only, closing and getting back to original workbook cleanly, and using saveas to "guarantee" page exists in form that will make publish to succeed more consistently.]

VBA fails to find a file

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