Error 91 displays after Application Quit instruction - excel

I have built an Add-In which is intended to be downloaded from the www. The Add-In will land up in the user computer's Downloads folder.
On being activated, the first phase of the Add-In's activty is to copy itself into the user's '/Microsoft/AddIns' folder using SaveAs. Then then "parent" Add-in closes itself and quits Excel. (On restarting Excel the "child" Add-In will be loaded and active.)
The code for this is
Sub CheckInstall()
'Several lines of code before this.
'They have been tested and seem to work well.
MyNewfileNm = TestBase & GCSAPPNAME
If IsInstalled(MyNewfileNm) Then
Application.DisplayAlerts = False
ThisWorkBook.SaveCopyAs MyNewfileNm
Application.DisplayAlerts = True
MsgBox "We're done, and Excel will close." & Chr(13) & _
"On reopening you will find 'ACBA Mapping' loaded and active in the ADD-INS tab."
Excel.Application.Quit
ActiveWorkbook.Close False
Else
ThisWorkBook.SaveCopyAs MyNewfileNm
If ActiveWorkbook Is Nothing Then
Workbooks.Add
Set oAddIn = Application.AddIns.Add(MyNewfileNm, False)
oAddIn.Installed = True
Else
Set oAddIn = Application.AddIns.Add(MyNewfileNm, False)
oAddIn.Installed = True
End If
MsgBox "We're done, and Excel will close." & Chr(13) & _
"On reopening you will find 'ACBA Mapping' loaded and active in the ADD-INS tab."
Excel.Application.Quit
ActiveWorkbook.Close False
End If
End Sub
This processes and copies itself as expected, but before the Application.Quit completes I get an Error Code 91. On clicking the error message, it simply resumes the instruction code.The result is precisely as expected.
However, I must either solve the problem generating the error message or suppress the error message. For the time being I cannot do either.
I'd be grateful for a solution.

This turned out to be a silly mistake on my part. The revised code below runs without an error. The only difference is the elimination of the instruction to close the ActiveWorkbook in the first portion if the primary IF statement. There was no open workbook available to be closed at that juncture.
Sub Check Install()
'Several lines of code before this.
'They have been tested and seem to work well.
MyNewfileNm = TestBase & GCSAPPNAME
If IsInstalled(MyNewfileNm) Then
Application.DisplayAlerts = False
ThisWorkBook.SaveCopyAs MyNewfileNm
Application.DisplayAlerts = True
MsgBox "We're done, and Excel will close." & Chr(13) & _
"On reopening you will find the " & NewMappingVersion & " version of 'ACBA Mapping' loaded."
Excel.Application.Quit
' In principle we haven't initiated a Workbook so there is no need to close it.
' ActiveWorkbook.Close False
Else
ThisWorkBook.SaveCopyAs MyNewfileNm
If ActiveWorkbook Is Nothing Then
Workbooks.Add
Set oAddIn = Application.AddIns.Add(MyNewfileNm, False)
oAddIn.Installed = True
Else
' This shouldn't be necessary, but leave it for the time being.
Set oAddIn = Application.AddIns.Add(MyNewfileNm, False)
oAddIn.Installed = True
End If
MsgBox "We're done, and Excel will close." & Chr(13) & _
"On reopening you will find 'ACBA Mapping' version " & NewMappingVersion & " loaded and active in the ADD-INS tab."
Excel.Application.Quit
ActiveWorkbook.Close False
End If
End Sub

Related

Automation error on main code, but working on back-up code - VBA Excel

So i have 2 workbooks that contains the same code because I have to check the code with somebody else.
But the thing is, on the back-up workbook everything is working just fine, but on the main one, I have a "Run-time error -2147467259(80004005): automation error - unspecified error when it comes to this piece of code If wb1.BuiltinDocumentProperties("Last Save Time") > wb2.BuiltinDocumentProperties("Last Save Time") Then
Does anybody knows what could go wrong ? When I use the watch windows, i can see that "wb1" properties are not taken into accounts, but for the "wb2" it works
full sub :
Sub Fyle()
Set fd = Application.FileDialog(msoFileDialogFilePicker)
MsgBox ("Please choose 2 files to comparer.")
check = 0
While check <> 2
With fd
.InitialFileName = FPath
.AllowMultiSelect = True
.Show
End With
check = fd.SelectedItems.Count
If check <> 2 Then MsgBox ("please choose only 2 files")
Wend
Set wb1 = Workbooks.Open(fd.SelectedItems(1))
Set wb2 = Workbooks.Open(fd.SelectedItems(2))
If wb1.BuiltinDocumentProperties("Last Save Time") > wb2.BuiltinDocumentProperties("Last Save Time") Then
Call order(wb2, wb1)
MsgBox ("Vous allez comparer " & wb2.name & " avec " & wb1.name)
Else
Call order(wb1, wb2)
MsgBox ("Vous allez comparer " & wb1.name & " avec " & wb2.name)
End If
wb1.Close False
wb2.Close False
End Sub
i tried to copy and paste the whole code (many subs being called from different modules) from the back-up workbook to the main, but the error remains here.

Error - Can't execute in break mode - VBA

Thanks for everyone that answers questions on here. I use this site all the time. I'm not formally trained but have put together some stuff in the past.
Here is what my Code accomplishes. I have a macro enabled excel file that I store in SharePoint. My users edit the excel and run a macro that saves their changes into a CSV File that we use to Import into JIRA. I've been able to create the macro to do all this and it works great when I used it. But when others in my group use it they are getting a "Can't execute in break mode" error. I think I'm missing some validation code but I'm not sure how to achieve this. Any help would be greatly appreciated! I'm so close!!
'''
Sub Save_CSV_Debugger()
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")
'Makes a copy of the Worksheet
ws.Copy
'Creates New FileName - Concatenates username and Desktop path with for
New Name
NewName = Environ("USERPROFILE") & "\Desktop\" & Range("A2").Value & " -
JIRA Import" & ".CSV"
Application.DisplayAlerts = False
'Saves WB with NewFileName
ActiveWorkbook.SaveAs Filename:=NewName, _
FileFormat:=xlCSV, CreateBackup:=False
Application.DisplayAlerts = True
'Hides saves dialog
If SaveAsUI = True Then Cancel = True
' Shows user a message
MsgBox "File saved to Desktop for JIRA Import " & vbNewLine & NewName
ActiveWorkbook.Close
'Reopens CSV File Without Macro - Clean CSV
Application.Workbooks.Open (NewName)
End Sub
'''

Picture not showing until sub has finished

I'm working on a project in Excel using VBA. I'm getting sheets from other workbooks, which takes a little time. For a userfriendly perspective, I'd like to show a picture saying "Loading" while the application gets the different sheets.
My problem is that the picture doesn't show before the Sub has finished. I've tried troubleshooting this myself.
I've tried running the code to insert the picture in another Sub being called. I've tried adding "DoEvents". I've tried adding an application wait. I've tried "ActiveWindow.SmallScroll" and "Application.Calculate" all without any luck.
I cannot see why the picture wouldn't show when the code is run.
If I add a break point in the code, the picture shows when I'd like it. I'm out of ideas and hope you can help me.
This is a snip of my code:
Sheet1.Activate
Application.Goto Reference:=Range("a1"), Scroll:=True
PicLoad = "PicLoad"
Sheet1.Pictures.Insert(Pictures & PicLoad & ".jpg").Name = PicLoad & "_picture"
Sheet1.Pictures(PicLoad & "_picture").Width = Application.Width
Sheet1.Pictures(PicLoad & "_picture").Left = 0
Sheet1.Pictures(PicLoad & "_picture").Top = 0
Sheet1.Shapes(PicLoad & "_picture").Line.Visible = msoTrue
Sheet1.Shapes(PicLoad & "_picture").Line.ForeColor.ObjectThemeColor = msoThemeColorText1
Sheet1.Shapes(PicLoad & "_picture").Line.Weight = 1
If ThisWorkbook.Path = requiredPath Then
Application.Run "Module4.HideCal"
For Each ws In ThisWorkbook.Worksheets 'Sletter alle worksheets undtagen nummer 1
If ws.Index <> 1 Then
ws.Delete
End If
Next
thisName = ThisWorkbook.Name
Workbooks.Open (requiredPath & "\" & fileComponents & "*.xl??"), ReadOnly:=True, CorruptLoad:=xlRepairFile 'f?r componenter ind
fileComponents = ActiveWorkbook.Name
total = Workbooks(thisName).Worksheets.Count
Workbooks(fileComponents).Worksheets(1).Copy _
after:=Workbooks(thisName).Worksheets(total)
Workbooks(fileComponents).Close
*Continues getting worksheets from different workbooks..
The Module4.HideCal contains:
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Everything works exactly as it should. The only problem is that the picture doesn't show until the sub has finished. I'd like to show it before the If statement.
Best regards
Check your Application.ScreenUpdating - if it is False, then you have told Excel not to show this. You will need to tell Excel to redraw/update the screen!
One method that sometimes forces the screen to redraw is
Application.WindowState= Application.WindowState
You may, just to be safe, also want to toggle the Application.ScreenUpdating around this:
Appliction.ScreenUpdating=True
Application.WindowState= Application.WindowState
Application.ScreenUpdating = False

Excel VBA Automation error: The object invoked has disconnected from its clients -- inconsistent error

There are a number of issues with this error, but none seem to match my case exactly so posting in the hope of some help.
I have a macro which takes all the files in a directory, opens them silently in a new (hidden) instance of Excel and does two "Save As" operations: one to a location on SharePoint and one to an archive folder. The purpose of this is that the files are produced by SAS in XML format with an XLS extension. Saving them as native XLSX reduces file size dramatically.
Each day we produce a number of files which we then run the macro on. It has been erroring on the same file each day; that is to say it's not exactly the same file, but the same report with different versions each day. It is the largest of the files, but other than that there's nothing outstanding about it.
There are two other oddities:
When running the code step-by-step with F8, the error doesn't occur - this has meant I've been unable to pinpoint exactly where it's erroring;
The code has an option to skip files that error - when skipping and rerunning it again immediately afterwards, with no other changes, the error doesn't occur the second time.
Here's the code; the macro is called different times with different locations as parameters:
Sub LoopThroughDirectory(inPath As String, sharepointPath As String, archivePath As String)
Dim sDir As String
Dim app As New Excel.Application
Dim wb As Excel.Workbook
Dim mbErr As Integer, mbFinished As Integer
If Right(inPath, 1) <> "\" Then inPath = inPath & "\"
On Error GoTo ErrHandler:
sDir = Dir$(inPath, vbNormal)
Do Until Len(sDir) = 0
On Error GoTo LoopError:
app.Visible = False
app.DisplayAlerts = False
Set wb = app.Workbooks.Add(inPath & sDir)
With wb
.SaveAs Filename:=sharepointPath & Left(.Name, InStrRev(.Name, ".")) & "xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False, ReadOnlyRecommended:=True
.SaveAs Filename:=archivePath & Left(.Name, InStrRev(.Name, ".")) & "xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close SaveChanges:=False
End With
Set wb = Nothing
app.DisplayAlerts = True
app.Quit
Kill (inPath & sDir) ' delete the file
NextFile:
sDir = Dir$ ' find the next filename
Loop
mbFinished = MsgBox( _
"The process has finished. You may need to review any files that have errored.", _
vbOKOnly, _
"Process finished" _
)
On Error GoTo 0
Exit Sub
ErrHandler:
mbErr = MsgBox( _
"There has been an error finding files. Check the SharePoint folder and try again.", _
vbCritical + vbOKOnly, _
"Error finding files" _
)
On Error GoTo 0
Exit Sub
LoopError:
Select Case MsgBox("There has been an error with " & sDir & "." & vbCrLf & vbCrLf & _
"The error is " & vbCrLf & vbCrLf & _
Err.Description & "." & vbCrLf & vbCrLf & _
"Press OK to continue with the next file or Cancel to stop the process.", _
vbCritical + vbOKCancel, "Error")
Case vbOK
Resume NextFile ' go back and try the next file
Case vbCancel
On Error GoTo 0
Exit Sub ' stop processing the files
End Select
End Sub
I suggest to insert the sub below underneath your existing code, outside your procedure but in the same code module.
Private Sub WaitASecond(ByVal Sec As Single)
Dim WaitTill As Single
WaitTill = Timer + Sec
Do
DoEvents
Loop While Timer < WaitTill
End Sub
Call it from your main procedure with a line of code like this.
WaitASecond(0.5) ' which would wait for half a second
Experiment with both the length of time, in increments of 0.25 seconds, if you like, and the location of the code. Bear in mind that it seems that your biggest file creates the problem. So, you might limit the call to that one file or vary the length of the wait depending upon the file size (if it makes a significant difference to your process).
You might instroduce a wait after each SaveAs, only after both SaveAs and/or after the Kill.

VBA hangs when opening Excel files

I have a macro which loops through a list of Excel filepaths. The macro will read each path, open the workbook, copy/pull data out of each workbook and then pastevalues the data into a central workbook. There are about 2000 filepaths.
After a while (maybe after it has looped through the first 70 or so filepaths), Excel hangs. It shows the "Downloading" message box that you get when opening a file. If I click cancel on the msg box, the workbook opens and the macro continues as normal.
I would have to sit here for 1000s of filepaths. Why does Excel get stuck here? Is there a way around it?
This message box does not happen on every Workbooks.Open instance, just after every few.
Example of the code:
With ThisWorkbook.Sheets("Filepaths")
For i = firstrow To lastrow
SourceFile = .Cells(i, 1).Value
Workbooks.Open SourceFile, ReadOnly:=True
Set MyFile = Workbooks(Workbooks.Count)
' ..more code..........
' ..more code..........
' ..more code..........
MyFile.close
Next i
End With
Thanks for the comments. These are both good points (and are both solutions I believe I have tried in the past). But just to check, I modified my Workbooks.Open line:
Application.DisplayAlerts = False
Workbooks.Open SourceFile, ReadOnly:=True, UpdateLinks:=False
Application.DisplayAlerts = True
But the message box is still popping up.
What's weird is when I step thru line by line, after I step past the Application.DisplayAlerts = False line, when I hover over the "Application.DisplayAlerts" variable, it still says true?
Seems like you are trying to open a file from a shared drive and that is why it is showing you the "Downloading" message box. This happens sometimes.
Application.DisplayAlerts = False in such scenario will not help. Nor will ReadOnly:=True, UpdateLinks:=False help.
Try this code (Untested)
With ThisWorkbook.Sheets("Filepaths")
For i = firstrow To lastrow
SourceFile = .Cells(i, 1).Value
'~~> Check for network path and use sendkeys
'~~> to close the downloading window
If InStr(1, SourceFile, "\\") Then _
Application.SendKeys "~", True
Workbooks.Open SourceFile, ReadOnly:=True
Set MyFile = Workbooks(Workbooks.Count)
'..more code..........
'..more code..........
'..more code..........
MyFile.Close
Next i
End With

Resources