When is an extension required in workbook name? [duplicate] - vba

This question already has an answer here:
Excel VBA requiring file extension for workbook reference in some systems
(1 answer)
Closed 3 years ago.
I have a directory of excel files that interact with each other through VBA code in a master file.
I've never had a problem with this before, but after copying the whole directory to do some development work on the copy (keeping the original intact in a different location) I'm running into a "subscript out of range" problem when referencing the workbook.
For example, everything ran fine previously with this line of code (nothing in the actual code has been changed):
Code that now throws an error (never used to):
ScheduleLocation = Workbooks("Master Schedule").Path
However, this line now throws an error. If I replace "Master Schedule" with "Master Schedule.xlsm" everything works again. I've had this problem before, but I've never been able to put a finger on the root cause of the problem.
Code that doesn't throw an error:
ScheduleLocation = Workbooks("Master Schedule.xlsm").Path
Hence my question: why is this? Why would the name (without extension) be insufficient sometimes, and sometimes not?

Have you got "Show file extension of known file types" turned on in windows explorer?
Try to run the code with hidden and visible extensions.
It is good practice to assign the workbook to variable on open.
Dim wbInput as Workbook
Set wbInput = Workbooks.open ("C:\Master Schedule.xslx")
Now you can work on variable without caring about the system settings for extensions.

Related

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.

Strange issue with str function versus Str

I have one of the stranges problems I have encountered for many years. I have a Workbook with a lot of code that validates the users data and has been used for many years now. A user reported that the latest version of the file was crashing excel and giving him an "automation error". To my knowledge the changes made to the most recent file were minor and should not have caused this. On analysis the cause of the problem was straight forward, but how it happened, why it happened and how to fix it, I do not know.
The issue occurred due to the below line of code, which is expecting a numeric, but the user supplied a string:
Ltrim(Str(Usersdata(UsersDataRow,UUID_Col)))
Note the upper case S on str. The previous version of the workbook has the same line but str is in all lower case, and does NOT crash excel.
Both files syntax check perfectly. But the strangest thing is when I have both old and new version of the file open in the VBA editor.
If I edit the line in the old file and change str to Str, the editor autocorrects it back to all lower case str.
If I edit the new workbook and change Str to str, the editor autocorrects it back to init cap Str.
So as it stands, I cannot correct the new file.
This behaviour is very strange and am hoping someone can tell me how it has happened and possibly how to solve it?
Regarding fixing the main problem I suggest replacing the line
Ltrim(Str(Usersdata(UsersDataRow,UUID_Col)))
with a more thorough input validation that can handle alphanumeric values
.
As Siddharth Rout suggested in the comments:
The symptoms you describe indicate that the VBA name space has been corrupted
The most common source are variable names like "str", "val", "name", "file", "count", "cell", "row" etc
A quick way to check name conflicts is to click inside the variable name and press F1;
the Help should show "Keyword Not Found"
.
The experiment bellow can demonstrate the problem: open a new Excel, and Alt + F11 for VBA
paste this code in a standard module:
Sub test1()
Dim txt As String 'valid variable name
txt = Str("123") 'Str() remains with a capital S
End Sub
.
Now replace the code with this (obvious problem):
Sub test2()
Dim str As String 'invalid variable name
str = str("123") 'Str() is converted to lower case "s"
End Sub
.
VBA is now corrupted and here is one way to fix it:
close the file
reopen it, and do not allow macros to run
open VBA editor (Alt + F11)
perform a Search and Replace in all VBA modules for "str" (replace "str" with "Str")
Match Case
Find Whole Word Only
Current Project <-- most important setting
The Replace operation will be performed only once, because VBA will automatically convert all other instances of "str" to "Str" before any other replacements
Name space is now restored the next time you open the file
(the procedure forces a recompilation of the P-code generated for all modules)
Another way to re-generate clean P-code is to export each individual standard module as *.bas files, *.cls for Class modules, and *.frm for user forms code, and import all into a new Excel file

PowerPoint 2013 macro keeps file locked open after close command

I have a PowerPoint VBA function that opens presentations, copies slides into the active presentation, then closes the source presentation. It worked fine in 2010, but fails in 2013 (all on Windows 7) if it tries to open the same presentation more than once. It appears to me that after the presentation.close command is issued, the window is closed, but the file remains locked open until the VBA code exits. So if the code attempts to open that file again it returns the error:
"Method 'Open' of object 'Presentations' failed"
Here's a simplified form of the function I'm running that behaves the same way. I've had a colleague test this again in PowerPoint 2010 and it runs fine. I've also had a colleague test it under his 2013 to make sure it's not something with my particular installation.
Sub testopen()
Dim ppFile As Presentation
Dim i As Integer
Const fpath = "C:\test.pptx"
For i = 1 To 2
Set ppFile = Application.Presentations.Open(fpath)
ppFile.Close
Set ppFile = Nothing
Next i
End Sub
The file test.pptx is just a blank presentation. In debug mode I can see the file opens and closes on the first loop, then on the second loop the open command fails and I can see in Windows explorer that the hidden temporary file still exists, indicating the file is still open, until I exit the VBA code. I also verified that the file is held open by adding in a function to check the file open status.
I've spent probably an hour googling this and cannot find any other descriptions of this problem. I'm sure I can implement a workaround but it's driving me crazy that I can't find any other reports of seemingly such a simple issue. Any suggestions are greatly appreciated! Thanks.
The Best way that I have achieved this is to simply create a VBS file and in the VBS file I call out the desired VBA code. It's little more hassle than to write the VBA code, but it's the solution that worked for me.
For example in the VBS file:
Dim args, objPP
Set args = WScript.Arguments
Set objPP = CreateObject("Powerpoint.Application")
objPP.Open "C:\path\to\file.ppx"
objPP.Visible = True
objPP.Run "The_Macro"
objPP.Save
objPP.Close(0)
objPP.Quit
Or better yet, have the entire code within the VBS file and have it copy the desired slides.
Hope this helps you achieve your result.
Setting the file as Read Only resolved the issue. The open command is now:
Set ppFile = Application.Presentations.Open(fpath, msoTrue)
Also, saving the file before closing it resolved the issue. For that, add:
ppFile.Save
Interestingly, I had already tried setting the Saved property to True (ppFile.Saved = msoTrue), which does NOT work. Thanks to Michael for his suggestion on the VBS script. That does work and I had never run an external VBS script so I learned something new. In this case, I'd prefer to stick with a VBA solution.

Can't open xlsm file from SSIS package job

I have a number of SSIS jobs that open some Excel files and manipulate them. The task within the job that opens the Excel file is basically the same in each job, it just points to a different Excel file. Each of these jobs work fine except for one. But even this one works when ran manually from the package and not in the job.
The applicable code is:
Dim reportLocation As String
Dim oXL As Microsoft.Office.Interop.Excel.Application
Dim oWB As Microsoft.Office.Interop.Excel.Workbook
reportLocation = "\\testlocation\share\test.xlsm"
'Open Excel instance
oXL = New Microsoft.Office.Interop.Excel.Application
oXL.Visible = False
'Open the Excel file to edit
oWB = oXL.Workbooks.Open(reportLocation) 'Error here
The error received is as below:
Microsoft Excel cannot access the file '\\testlocation\share\test.xlsm'.
There are several possible
reasons:
• The file name or path does not exist. • The file is being used by
another program. • The workbook you are trying to save has the same
name as a currently open workbook. at
Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object
UpdateLinks, Object ReadOnly, Object Format, Object Password, Object
WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin,
Object Delimiter, Object Editable, Object Notify, Object Converter,
Object AddToMru, Object Local, Object CorruptLoad) at
ScriptTask_ffa2c543b1224c3987d5764694df1079.ScriptMain.Main()
This was the latest package to be created, and was a copy/paste job, just changing the locations it looks for the files. I have checked all permissions and there is no issue there. I've even given access to "Everyone" to see if that was an issue, but the same error occurred. The file definitely exists in the location and it is not open by anyone. What possible reason is there that this specific file can't be opened when run in a SQL job but can be opened when run manually in the package? I have also tried changing the job to run the package as a user with full admin access via a proxy. But still no joy.
This does not look like a valid path to me:
\\testlocation\test.xlsm
You at least need a share name after the host name:
\\testlocation\Share\test.xlsm
How do the paths look for your working files? I'm guessing they have a share.
Having revisited some answers on here for similar questions I was able to find the solution. This can be seen at Microsoft Office Excel cannot access the file 'c:\inetpub\wwwroot\Timesheet\App_Data\Template.xlsx'
I created the directory C:\Windows\SysWOW64\config\systemprofile\Desktop on the server and it miraculously now works. I had looked at this yesterday and thought the directory already existed so didn't implement this solution. But having a second look at it today shows the directory didn't exist and creating it fixed it.
Now the question is, why does this work?! But that is possibly another question.

Release a file from excel generated by VBA to allow for moving of file

I am using some code in my excel document to open images, rotate them as appropriate and then save them to a temp folder (see How do I rotate a saved image with VBA?).
I am now trying to rename these generated images within the same folder using Name... as..., however this throws up an error, saying that the image is still in use by Excel ("File/Path access error" in VBA - it tells me its in use by excel when renaming it in an explorer window though)
Is there any way to "throw this out" of Excel using VBA before this stage? I did try Set p = Nothing (with p coming from Set p = .Pictures.Insert(Filepath)) but this still gives an error. The sheet that the new image is created from is deleted after it is saved to the temp folder so it does not exist on the sheet any more either. Once I fully close excel, I can rename the file again.
The "solution" I ended up with was to copy folder C:\Temp\a\ to C:\Temp\b\ and make the changes from there before copying to \\my\actual\location
This works OK as a decent workaround for this instance, but by no means a 100% complete answer to the question
YOUR CODE HERE.....
CLOSE
'by add "close" at the ending of your line before conducting the next action