Excel 'Cancel' button breaks entire application - vba

Having trouble with calling an endpoint (connectionStringURI = http:\company.com:8000/Prices?format=csv&Transaction.ID=5456, e.g.). Call it with this code:
Set curveSource = curveDestination.QueryTables.Add(Connection:="TEXT;" & connectionStringURI, Destination:=DestinationSheet.Range("A1:F3000"))
curveSource.Name = "Prices"
curveSource.TextFileParseType = xlDelimited
curveSource.TextFileCommaDelimiter = True
curveSource.Refresh BackgroundQuery:=False
curveSource.SaveData = True
The call to the URI returns a csv file. Everything works great. When this code is hit:
curveSource.Refresh BackgroundQuery:=False
I see an Excel dialogue box that says, "Contacting the server for information", and it has a 'Cancel' button on it. If the user does nothing, it displays the data properly in the DestinationSheet. If the user clicks the 'Cancel' button while this is occurring, it breaks the entire spreadsheet. From then on, it throws an error at
curveSource.Refresh BackgroundQuery:=False
The error is, "Run-time error: '1004'. Excel cannot find the text file to refresh this external data range". The user has to close the file the Excel file and reopen it to get it to work. Can't find anything about this error after hours of googling.
I've tried setting everything to Nothing, removing QueryTables, very frustrating. Nothing seems to fix the issue.
Any ideas ?

Not sure if this would help but you can try Application.DisplayAlerts = False before that line, and revert back to True afterwards maybe. And/or On Error Resume Next before the line that give the error and On Error Goto 0 afterwards.

Related

Multipage error: The object invoked has disconnected from its clients

So I've probably spent the last week researching/trying to fix this annoying error but to no avail. Here's what I'm trying to do and the error I'm getting:
I have a userform that contains 12 multipage pages and to access each one I have coded previous/next buttons. Now, One of these pages is disabled through properties to hide from the user, that is until a specific checkbox is clicked. When it's clicked, the page is enabled, and the user is now able to view this page as well as all the others. when the checkbox is clicked again (making it false and no longer true), the page hides from the user's sight. This is basically what I'm trying to accomplish. The pages are like so:
page1, page2, page3, page4, "page5", page6, etc.
As you can see, page5 is what is being disabled/enabled. Now also, something important to note, I've made the userform to appear before the workbook is actually visible using this:
Private Sub Workbook_Open()
Application.ScreenUpdating = False
ThisWorkbook.Application.Visible = False
OpeningWindow.Show
Windows(ThisWorkbook.Name).Visible = True
Application.Visible = True
Application.ScreenUpdating = True
End Sub
This I would like to avoid changing because it's vital that the userform appear first before the workbook because the workbook is acting as the storage/database for everything that is being typed in the userform using this multipage system. Now when I run the userform through VBA and test out this function "checkbox_click Enables/Disables multipage page", it works no problem. When I attempt to open it (as if you were starting up excel without anything opened) everything works fine, until I click the checkbox in question to enable the multipage to make it visible. This is where I'm getting the error "The object invoked has disconnected from it's clients". Now I've tried some other things out to see if I could get the same result:
Made the multipage page visible = False instead of Enabled = false.
Result: This somewhat works, however when attempting to click the previous button to go back a page (Page6 to Page5) when Page5 is visible = False, The previous button doesn't respond, as if it knows that Page5 is there even though it's invisible.
Anyway, to wrap things up, I would like to ask the community here if anyone knows exactly why, from the code I've provided below that is responsible for this "page enable/disable feature", I'm getting this object invoked has disconnected error and if there's a way to fix it.
Private Sub CheckBox119_Click()
If CheckBox119.Value = True Then
Me.MultiPage1.Pages(5).Enabled = True
CheckBox138.Value = True
Label309.Visible = True
Else
Me.MultiPage1.Pages(5).Enabled = False
CheckBox138.Value = False
Label309.Visible = False
End If
End Sub
CheckBox138 btw is located on Page5 and is there if the user wishes to click it to disable page5 and Jump to Page4, which is this code:
Private Sub CheckBox138_Click()
If CheckBox138.Value = False Then
MultiPage1.Value = 4
CheckBox119.Value = False
Label309.Visible = False
End If
End Sub
Also, I'm relatively new to coding in VBA, but I'm always ready to learn.
After some playing around, I believe I figured out what the problem was. The checkbox138 in the disabled page was the culprit. By deleting the code Private sub checkbox138_click(), it works now. I'm not entirely sure why this is the case (so someone with more knowledge may be able to explain) But When checkbox119 is clicked, checkbox138 is suppose to turn true being that's what the initial code expressed. However, even though making checkbox119 true is suppose to enable the disabled page followed by making checkbox138 true, there seems to be a hiccup. It seems checkbox138 is thinking the disabled page is still disabled (even though checkbox119 is suppose to enable it) therefore making the checkbox138 hidden.

How to stop Excel Macro Which Still Runs After Application.Quit Method

I have found similar questions, but for other issues, seems that Excel is called from another application and process is left after Excel application closes.
In my case, I have a macro in my Excel file, and I try to close the application when an error occurs.
I have my error handling set this way:
'Code code code
CleanExit:
Logger.LogData LOG_DEBUG, MODULE_NAME, "Initialize", "Some module initialized!"
Exit Function
ErrorExit:
Logger.LogData LOG_ERROR, MODULE_NAME, "Initialize", "Error found! Description: " & err.description
Main.HandleError err, MODULE_NAME, "Initialize"
GoTo CleanExit
End function
I want my macro to stop running when error occurs in some module and not to stop if it's in another module (hence the GoTo CleanExit).
Error handler is set-up in this way:
Public Function HandleError(ByRef err As ErrObject, ByVal moduleOrgin As String, ByVal methodOrgin As String)
Dim wbk As Workbook
'Do something if module origin meets my parameters and exit function right here if my conditions are met
MsgBox "Some message to the user about the problem"
If GetSetting(SETTING_HIDE_APPLICATION, False) = True Then
For Each wbk In addinWorkbook.Application.Workbooks
wbk.Saved = True
Next wbk
addinWorkbook.Application.Quit
End If
End Function
After this code runs I assume that all further code running stops, as my Excel workbook, which hosts my macro code is closed with the application.
In reality I get a cascade of errors, where the error message is shown 3 times until it closes for good. How can I avoid code any code running after Application.Quit method?
Code workflow when error occurs and what runs after Application.Quit:
Main method to initialize my form
Call to loader method which throws error (Application should quit here)
Main method continues after loader method is finished
Subsequent method is called from main method which also throws an error (because first loader failed)
Lastly my main method throws an error
In total I receive 3 msgboxes with error descriptions.
I must note, that I use the same error handling procedure in all methods, but I would like the code to stop executing, so further code does not trigger any errors.
How can I avoid code any code running after Application.Quit method?
If you want to stop everything, write End after Application.Quit. It stops every piece of VBA and kills all variables you have assigned. This is not considered a good practice (At all!), but it will work exactly as you want.

Disable Alert message of a webpage using VBA code

I am opening a webpage using VBA code which contains form where data will be filled by user. I have excel file which contains data. I write VBA code that read the data from excel and put it on webpage. After filling information on webpage I click on Save button. All this work I had done using VBA code so that it can be done automatically. I have 500 users data hence I run the loop 500 times. All it done fines.
Only one problem come and it is that after filling data in webpage form when I click on save button a popup message comes "Your data saved successfully". It has "OK" button. Now my program stops here and need user intervention to manually click on "OK" button.
Is there any way using VBA code by which we can stop this popup message box, so that manual intervention is no longer required?
I read the webpage and Javascript written for webpage also. I found that when Save button is clicked a function called savedetails() . Inside this function a alert() function is there. Sample code here
function saveDetails()
{
/* get details of member*/
---
---
---
---
---
if (xml.status == 200 || window.location.href.indexOf("http") == -1) {
var successCode = "";
alert("Data Saved Successfully");
var tes = xml.responseText;
/* if (successCode == '1') { */
document.webDataForm.submit();
remove_popup();
};
}
VBA Code For Each htmlInput In htmlColl
If Trim(htmlInput.ID) = "btn" Then
If Trim(htmlInput.Name) = "btnfinal" Then
htmlInput.Click 'After this "Data Saved Successfully popup message comes and program need user intervention
temp = htmlInput.getAttribute("onClick")
MsgBox temp
'IE.document.getElementById("clearRelItems").removeAttribute ("o n C l i c k")
'Call iedoc.parentWindow.execScript("window.confirm = function saveBankDetails() {return true}", "JavaScript") // Not worked
'htmlInput.removeAttribute ("onClick") //Not worked
'htmlInput.setAttribute "onClick", "return TRUE" //Not worked
'Application.SendKeys "{ENTER}", True // Not worked
Exit For
End If
End If
Next htmlInput
You could try wrapping the line with the Application.DisplayAlerts function that produces the display box you don't want;
eg.
If Trim(htmlInput.ID) = "btn" Then
If Trim(htmlInput.Name) = "btnfinal" Then
Application.DisplayAlerts = False
htmlInput.Click
Application.DisplayAlerts = True
.... Further Code
I had this problem and the only way I could solve it was by writing a vb script that identifies the pop up and closes it...
After that, you just need to call it from your vba code.

Closing the VBA Editor Window

I am trying to close my Visual Basic Editor window. I couldn't find any perfect code for this. These are the previous suggested codes i have tried,
1) Application.VBE.MainWindow.Close
2) Application.VBE.ActiveWindow.Close
3) Application.VBE.ActiveCodePane.Window.Close
If I run any of these codes, i am getting the following Run time error(6068)
"Programmatic Access to Visual Basic Project is not trusted".
Please tell me if there is any solution for this problem.
Application.ShowVisualBasicEditor = False
Application.VBE.MainWindow.Visible = False
tested with:
Sub hideVBE()
MsgBox "foo"
Application.VBE.MainWindow.Visible = True
MsgBox "bar"
Application.VBE.MainWindow.Visible = False
End Sub

Exporting Charts of Access to Image Format?

I have created a chart in Access forms and exported it in Image Format. It's easily done, but the problem comes when after it, when I close the Form, It Shows a Pop-up message.
"The operation on the Chart object failed.
The OLE server may not be registered.
To register the OLE server, reinstall it. "
Then I have done some change and the Code looks Like:
Private Sub Command1_Click()
Dim grpApp As Graph.Chart
Set grpApp = Me.Graph1.Object
grpApp.Export "C:\Graph1.jpg", "JPEG"
Me.Graph1.Enabled = True
Me.Graph1.Locked = False
Set grpApp = Nothing
Me.Graph1.Action = acOLEClose
End Sub
Now the problem is that after the export is done, the chart becomes bad, the fonts were big
and condensed and the bars looked short...
I'm really stuck..
After trying various workarounds, I found pretty much the same question and a proper fix for the problem:
Try unlocking the graph before the export, and restore the lock afterwards
'Unlock the control...
Me!YourOLEChart.Locked = False
Me!YourOLEChart.Enabled = True
'Do the actual export...
Set oleGrf = Me!YourOLEChart.Object
oleGrf.Export filename, "JPEG"
Set oleGrf = Nothing
Me!YourOLEChart.Action = acOLEClose
'Restore the lock...
Me!YourOLEChart.Locked = True
Me!YourOLEChart.Enabled = False
Important: remember to set the Action acOLEClose to avoid the OLE server from crashing.
You are not aloneā€”I had the same problem. On several runs of the form, after the export execution, the chart/graph/OLEFrame became wrong (on the form View), its format got changed and I hadn't known why.