doCmd OpenQuery and RunMacro failed after moving database to New Folder - vba

I have a database ready to be deployed with front end using excel. I'm using a combination of ADO and DAO to connect to access db. ADO is mainly for retrieving, updating and view data while DAO is mainly use for running access query or macros using openquery and runmacro method.
The issue start when i have move the database to new folder. My ADO connection is working fine after changing database path which i store in a variable string. However when it come to running access query and macro using DAO connection, it fail to run both query and macros. I have set progress bar to monitor the progress and i can see DAO successfully open connection to database but as soon as it reach to the .docmd.openquery or .docmd.runmacro it failed to run. The only error given is "The OpenQuery action was cancelled" or The "RunMacro action was cancelled"
Below are my full code. I'm changing from path "Y:\1_Year_2018\2_Admin_Main_Files\0_Database\2023\Database.accdb" to path "P:\Database.accdb"
Nothing is changing both in Access DB and Excel VBA. Only the location of the accdb been moved to P drive.
Is there some hidden link that i'm not aware of.
Dim AC As Object
Set AC = CreateObject("Access.Application")
Dim strDatabasePath As String
strDatabasePath = "P:\Database.accdb"
' strDatabasePath = ThisWorkbook.Path & "\Database.accdb"
Call ProgressBar.Progress(5)
Application.Wait (Now + TimeValue("0:00:01"))
With AC
.OpenCurrentDatabase (strDatabasePath)
Call ProgressBar.Progress(30)
Application.Wait (Now + TimeValue("0:00:01"))
Dim db As Object
Call ProgressBar.Progress(50)
Application.Wait (Now + TimeValue("0:00:01"))
Set db = .CurrentDb
Call ProgressBar.Progress(70)
Application.Wait (Now + TimeValue("0:00:01"))
.DoCmd.SetWarnings False
.DoCmd.OpenQuery "qryUpdateInternalInvListing1"
.DoCmd.OpenQuery "qryUpdate_ItnlNo_toCarrierInvSummary1"
.DoCmd.SetWarnings True
.Quit
End With
ActiveWorkbook.RefreshAll
Call ProgressBar.Progress(90)
Application.Wait (Now + TimeValue("0:00:01"))
Call ProgressBar.Progress(100, False)
ProgressBar.Hide
Application.ScreenUpdating = True
I have tried remove library reference and re-reference again. Rewriting the code from scratch again and tried to re-create the query in accdb and name it differently, but still nothing works. When i move the database back to old path, everything works 100%.

Related

Trying to use VBA to Open a PowerBI File, Refresh it, and Save it?

I am trying to open a .pbix file that sits on a network drive, refresh the PowerBI connection to the file, then close the file and save the changes. I am trying to run the process from Excel, because Excel does some things, propr to this refresh task. I am testing the code below, which I think is pretty close, but I an getting this error message:
RUN TIME ERROR: 424 Object Required
Public vPID As Variant
Sub Launch_Calculator()
Dim fileString as String
If IsProcessRunning("C:\Program Files\PBIDesktop.exe") = True Then
On Error GoTo Reload ' Open new instance of PBIX
AppActivate (vPID) ' Reactivate, using Public declared variant
SendKeys "%{Enter}" ' Bring it back into focus if user minimises it
Else
Reload:
fileString = """\\network_path_here\testing.pbix"""
strFileName = CreateObject("WScript.Shell").Specialfolders("\\network_path_here\") & "testing.pbix"
' fileString.Open...got RUN TIME ERROR: 424 Object Required
' strFileName.Open...got RUN TIME ERROR: 424 Object Required
End If
On error GoTo 0
End Sub
' Function to check for running application by its process name
Function IsProcessRunning(sApp As String)
On Error GoTo Skip
Dim objList As Object
Set objList = GetObject("winmgmts:") _
.ExecQuery("select * from win32_process where name='" & sApp & "'")
If objList.Count > 0 Then
IsProcessRunning = True
Exit Function
Else
IsProcessRunning = False
Exit Function
End If
Skip:
IsProcessRunning = False
End Function
So, I can open the PowerBI.exe file, and run the application just fine, but I can't open and refresh the '.pbix' file. How can I open the .pbix file, refresh it, and save it?

VBA Auotmation - Closing IE Before IE.Quit Runs Freezes Excel

I have some code which closes IE after some VBA Website Automation (after waiting for a period of time).
Application.Wait (Now + TimeValue("00:00:55"))
IE.Quit
Set IE = Nothing
Set doc = Nothing
The problem is that if someone inadvertently closes IE before the IE.Quit code executes, Excel freezes because the IE property no longer exists.
I've tried something like this (please see below code excerpt) but Excel still freezes if it's closed before the timer executes the code (Run-Time error '462', The remote server machine does not exist or is unavailable):
Application.Wait (Now + TimeValue("00:00:55"))
If IE Is Nothing Then
'do nothing
Else
IE.Quit
Set IE = Nothing
Set doc = Nothing
End If
Any ideas or guidance would be much appreciated.
I'm agree with what Mathieu says. The freeze is due to the waiting is still being executed. Everything you put after Application.Wait will be executed after the waiting--which is to say after "the freeze".
You can only add On Error Resume Next after Application.Wait (Now + TimeValue("00:00:55")) to avoid the error display, but you can't stop the waiting.

How to extract PDF document from SAP GUI? (scripting)

I am trying to extract a PDF document from SAP, however, I am stuck with the second part of the code where I need to initiate the Save As sequence.
The first part of the code involves connecting to SAP and querying specific invoice number, followed by a few lines of code where I am trying to attach to the second SAP window containing the PDF document. The trick is using the Send Keys to save the actual file.
Sub DocumentExtraction()
Dim varResponse As Variant 'Prompts the user if macro should be run.
varResponse = MsgBox("Are you sure you wish to run extraction macro?", vbYesNo, "Warning!")
If varResponse <> vbYes Then Exit Sub
Set SapGuiAuto = GetObject("SAPGUI") 'Obtains SAP GUI Scripting object.
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Obtains currently running SAP GUI.
Set SAPCon = SAPApp.Children(0) 'Obtains the first system currently connected.
Set session = SAPCon.Children(0) 'Obtains the first session (window) on that connection.
' SAP scripting starts here.
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nFB03"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/txtRF05L-BELNR").Text = "930502016"
session.findById("wnd[0]/usr/ctxtRF05L-BUKRS").Text = "7360"
session.findById("wnd[0]/usr/txtRF05L-GJAHR").Text = "2019"
session.findById("wnd[0]/usr/txtRF05L-GJAHR").SetFocus
session.findById("wnd[0]/usr/txtRF05L-GJAHR").caretPosition = 4
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/titl/shellcont/shell").pressContextButton "%GOS_TOOLBOX"
session.findById("wnd[0]/titl/shellcont/shell").selectContextMenuItem "%GOS_VIEW_ATTA"
session.findById("wnd[1]/usr/cntlCONTAINER_0100/shellcont/shell").selectedRows = "0"
session.findById("wnd[1]/usr/cntlCONTAINER_0100/shellcont/shell").doubleClickCurrentCell
Set session = SAPCon.Children(1) 'Obtains the second session (window) on current connection.
session.findById("wnd[0]/shellcont/shell/shellcont[1]/shell").SetFocus
End Sub
I have found a similar post on the SAP support page, however, the suggested solution does not seem to work - an object does not exist.
An easy workaround was to disable Adobe PDF Reader in Internet Explorer by navigating to Internet Explorer/Tools/Internet Options/Programs/Manage add-ons/select All add-ons/disable Adobe PDF Reader.
Then use the code below after clicking on the document and it opens the open/save/close window.
Application.Wait Now + TimeValue("0:00:15")
SendKeys "%s" 'ALT + S initiates save as procedure.
Application.Wait Now + TimeValue("0:00:05")
SendKeys ExtractFolderPath & ExtractFileName 'File name and path are entered.
Application.Wait Now + TimeValue("0:00:02")
SendKeys "{ENTER}"
Application.Wait Now + TimeValue("0:00:02")
SendKeys "{F3}" 'Closes Document Viewer window.
Application.Wait Now + TimeValue("0:00:02")
session.findById("wnd[1]").Close 'Closes Attachment List window.

Refreshing and Saving as a text file in Excel

I have been trying to automatically refresh my table (obtained from an SQL database via power query) and directly save it as a text file (tab delimited)
I'm very new with VBA and the macro i used is
Public Sub UpdatePowerQueries()
'Macro to update the Power Query script(s) and save the file as .txt
Dim cn As WorkbookConnection
For Each cn In ThisWorkbook.Connections
If Left(cn, 13) = "Power Query -" Then cn.Refresh
Next cn
Application.DisplayAlerts = False
ActiveSheet.SaveAs Filename:="customfile" & Format(Date, "yyyymmdd") & ".txt", FileFormat:=xlTextWindows
Application.DisplayAlerts = True
End Sub
now the issue I've been facing is that the refresh part and the save part work ok on their own, but if I put them in the same macro, the save part happens too soon, and the text file is empty. Can anyone help me ?
Thanks
Personnaly, I have choose to be a bit patient and added a timer to go on after a few seconds!
Try to add this in between :
DoEvents
Application.Wait (Now + TimeValue("0:00:05"))
DoEvents

Reading Web Pages using Excel VBA

I want to read web pages using Excel VBA. How do I carry out this task? Is it even possible?
Coming from Excel 2003, yes this is possible - you may use the SHDocVw.InternetExplorer and MSHTML.HTMLDocument objects to call a web page, gain control over and interact with the DOM object. After creating references to Microsoft HTML Object Library (...\system32\MSHTML.TLB) and Microsoft Internet Control (...\system32\ieframe.dll) you can play with the following example:
Sub Test()
Dim Browser As SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Set Browser = New SHDocVw.InternetExplorer ' create a browser
Browser.Visible = True ' make it visible
Application.StatusBar = ".... opening page"
Browser.navigate "http://www.google.com" ' navigate to page
WaitForBrowser Browser, 10 ' wait for completion or timeout
Application.StatusBar = "gaining control over DOM object"
Set HTMLDoc = Browser.document ' load the DOM object
WaitForBrowser Browser, 10
' at this point you can start working with the DOM object. Usefull functions are
' With HTMLDoc
' .getElementByID(string)
' .getElementsByTagName(string)
' .getElementsByName(string)
' .getAttribute(string)
' .setAttribute string, string .... to change field values, click a button etc.
' End With
Application.StatusBar = "" ' time to clean up
Browser.Quit
Set HTMLDoc = Nothing
Set Browser = Nothing
End Sub
Sub WaitForBrowser(Browser As SHDocVw.InternetExplorer, Optional TimeOut As Single = 10)
Dim MyTime As Single
MyTime = Timer
Do While Browser.Busy Or (Timer <= MyTime + TimeOut)
DoEvents
Loop
' if browser still busy after timeout, give up
If Browser.Busy Then
MsgBox "I waited for " & Timer - MyTime & " seconds, but browser still busy" & vbCrLf & _
"I give up now!"
End
End If
End Sub
You can use VBA to automate IE (plenty of examples via Google) or you can fetch the page directly using an instance of MSHTTP (ditto plenty of examples on the web). Which is best for your needs will depend on exactly what you want to do. Hard to say more without more detailed requirements.