xlwings create AutomationServer Object - pywin32

I have an xlwing app that currently connects through Excel VBA (called in xlwings) to an xll-based Add-In to logon and refresh data.
This works fine, but I now would like to get rid of the Excel-part and move it to xlwings.
This is the VBA I'm using:
Sub LogonAndRefresh()
Dim bSuccess As Boolean
Dim CognosOfficeAutomationObject As Object
Dim Reporting As Object
Dim invokeAddin As Object
Set CognosOfficeAutomationObject = Application.COMAddIns("CognosOffice12.Connect").Object.AutomationServer
Set Reporting = CognosOfficeAutomationObject.Application("COR", "1.1")
Set invokeAddin = Reporting
CognosOfficeAutomationObject.SuppressMessages True
bSuccess = CognosOfficeAutomationObject.Logon("https://server.net", "domain\user", "password", "CAM_name")
bSuccess = CognosOfficeAutomationObject.Logon("https://server.net", "domain\user", "password", "DB_name")
CognosOfficeAutomationObject.SuppressMessages False
If (bSuccess) Then
CognosOfficeAutomationObject.ClearAllData
CognosOfficeAutomationObject.RefreshAllData
End If
End Sub
I can with xlwings:
for addin in app.api.COMAddIns:
print(addin.description)
and:
test = app.api.COMAddIns('CognosOffice12.Connect').Connect
returns True
but i think the issue is with .Object.AutomationServer:
test = app.api.COMAddIns('CognosOffice12.Connect').Object.AutomationServer
returns an error:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'CognosOfficeInterfaceAddin12', 'AutomationServer object only available on a STA.', None, 0, -2146233088), None)
Any suggestions or examples how this could be done?

Related

VBA Run-time error '380': A script engine for the specified language can not be created

This is more of general question, I suppose, as-well-as help with a specific line of code.
I have an Excel file that I was working on just a few days ago that was working fine, however now whenever I try to run the macro in the workbook to pull data from a website, I receive the error "Run-time error '380': A script engine for the specified language can not be created."
Here is the code block where I am running into the issue. I have starred the specific section where the error is thrown.
Dim H As Object, S As Object, jParse As Object, X64 As Object, i&
Set H = CreateObject("WinHTTP.WinHTTPRequest.5.1")
H.SetAutoLogonPolicy 0
#If Win64 Then
Set X64 = x64Solution()
X64.execScript "Function CreateObjectx86(sProgID) Set CreateObjectx86 = CreateObject(sProgID): End Function", "VBScript"
Set S = X64.CreateObjectx86("MSScriptControl.ScriptControl")
#Else
Set S = CreateObject("ScriptControl")
#End If
***S.Language = "JScript"***
S.AddCode "function keys(O) { var k = new Array(); for (var x in O) { k.push(x); } return k; } "
I have never seen this error before and I am not sure how to fix this issue. I have looked online and have thus far been unsuccessful in figuring out the problem. I have also tried downloading and installing the zip file from Microsoft in this link: https://gallery.technet.microsoft.com/scriptcenter/Registry-key-to-re-enable-835fba77 with no success.
Any help would be appreciated, because I really don't know what to do here.
Also if Stack Overflow is not really the place for this kind of question, any help in directing me somewhere that would be better suited for this kind of problem would be appreciated.
I just had a similar encounter attempting to use JScript to parse some JSON from the SO API using a x64 machine.
Disclaimer: I did not author the following procedures, but unfortunately I do not have the source of where I obtained them either.
As you've probably already figured out, MSScriptControl.ScriptControl doesn't like the x64 architecture very well. Here are a couple of functions that will allow you to do what you need.
I placed these in a separate module:
Public Function CreateObjectx86(Optional sProgID, Optional bClose = False)
Static oWnd As Object
Dim bRunning As Boolean
#If Win64 Then
bRunning = InStr(TypeName(oWnd), "HTMLWindow") > 0
If bClose Then
If bRunning Then oWnd.Close
Exit Function
End If
If Not bRunning Then
Set oWnd = CreateWindow()
oWnd.execScript "Function CreateObjectx86(sProgID): Set CreateObjectx86 = CreateObject(sProgID): End Function", "VBScript"
End If
Set CreateObjectx86 = oWnd.CreateObjectx86(sProgID)
#Else
Set CreateObjectx86 = CreateObject(sProgID)
#End If
End Function
Private Function CreateWindow()
Dim sSignature, oShellWnd, oProc
On Error Resume Next
sSignature = Left(CreateObject("Scriptlet.TypeLib").GUID, 38)
CreateObject("WScript.Shell").Run "%systemroot%\syswow64\mshta.exe about:""about:<head><script>moveTo(-32000,-32000);document.title='x86Host'</script><hta:application showintaskbar=no /><object id='shell' classid='clsid:8856F961-340A-11D0-A96B-00C04FD705A2'><param name=RegisterAsBrowser value=1></object><script>shell.putproperty('" & sSignature & "',document.parentWindow);</script></head>""", 0, False
Do
For Each oShellWnd In CreateObject("Shell.Application").Windows
Set CreateWindow = oShellWnd.GetProperty(sSignature)
If Err.Number = 0 Then Exit Function
Err.Clear
Next
Loop
End Function
Then you can go back to your S object and set it this way:
Dim S As Object
Set S = CreateObjectx86("MSScriptControl.ScriptControl")
S.Language = "JScript"

Dim As Dictionary. Compile Error: User-defined type not defined

Can you please assist with this problem?
Whenever I run this macro, it stops at:
Dim authResult As Dictionary
With an error message of:
Compile error: User-defined type not defined.
I have not used the dictionary type before and I am trying to re-use this code from a sample macro.
The aim of this script is to use excel to make rest calls to a website so that I can download historic data. I am currently stuck at the login section.
Sub Login()
Dim userName As String
Dim password As String
Dim apiKey As String
userName = "username"
password = "password"
apiKey = "key123"
'activityTextbox.Text = ""
'clearData
Dim authResult As Dictionary
Set authResult = restClient.authenticateAccount(userName, password, apiKey)
If Not authResult Is Nothing Then
'appendActivity "Connected"
' Configure Excel to pull streaming updates as often as possible
Application.RTD.ThrottleInterval = 0
' Uncomment for real-time prices - this is very CPU intensive
' Buffer interval defaults to 500ms
'Application.WorksheetFunction.RTD "IG.api.excel.RTD.IGApiRTDServer", "", "bufferInterval", "0"
' Set manual refresh to true from very remote locations
' Application.WorksheetFunction.RTD "IG.api.excel.RTD.IGApiRTDServer", "", "manualRefresh", "true"
' This will require manually calling refresh to update lighstreamer subscriptions, i.e.
' Application.WorksheetFunction.RTD "IG.api.excel.RTD.IGApiRTDServer", "", "refresh"
Dim maxPriceRequestsPerSecond As Double
maxPriceRequestsPerSecond = 0 ' all available updates
If restClient.streamingAuthentication(maxPriceRequestsPerSecond) Then
m_loggedIn = True
'populateWatchlists
'populateAccounts
'manualStreamingRefresh
'Else
' appendActivity "Lightstreamer connection failure"
End If
Else
MsgBox "Authentication failed"
End If
End Sub
Thanks in advance.
Cheers,
Joe
Add a reference to Microsoft Scripting Runtime as #YowE3k said:
In the VBA Editor:
Tools -> References
Find Microsoft Scripting Runtime
Check it
Click okay

excel VBA web service give error METHOD OR DATAOBJECT NOT FOUND

I have a weird problem with an excel VBA application.
It uses a web service to connect to a mysql database.
it all runs well in most computers....however in some computers it throws an error:
ERROR WHEN COMPILING "METHOD OR DATAOBJECT NOT FOUND"
All computers are running Windows 7 and Office 2007.
Here is an example of the web service code (where the error happens)
Public Function wsm_get_portscountries(ByVal str_SQLQuery As String) As MSXML2.IXMLDOMNodeList
On Error GoTo wsm_get_portscountriesTrap
Set wsm_get_portscountries = sc_WebService1.wsm_get_portscountries(str_SQLQuery)
Exit Function
wsm_get_portscountriesTrap:
WebService1ErrorHandler "wsm_get_portscountries"
End Function
The error highlights the bolded part here:
sc_WebService1.wsm_get_portscountries(str_SQLQuery)
Has anyone encountered the same problem ?? Any ideas ??
As I said, on most computers it runs well, no problems, it only happens with some.
Thanks in advance.
additional information:
class module
Private Sub Class_Initialize()
On Error GoTo Class_Initialize_error
Dim str_WSML As String
str_WSML = ""
Set sc_WebService1 = New SoapClient30
sc_WebService1.MSSoapInit2 c_WSDL_URL, str_WSML, c_SERVICE, c_PORT, c_SERVICE_NAMESPACE
sc_WebService1.ConnectorProperty("ProxyServer") = "<CURRENT_USER>"
sc_WebService1.ConnectorProperty("EnableAutoProxy") = True
Exit Sub
Class_Initialize_error:
End Sub

SAP RFC call returns "Error 0" in RETURN parameter from vb

Hi everybody and thanks in advance.
I'm trying to call a SAP BAPI using RFC from vb but I'm having some problem to get the result of the call.
The BAPI "BAPI_GL_ACC_EXISTENCECHECK" (from General Ledger Account module) has two parameters,
COMPANYCODE and GLACCT, and a RETURN parameter.
I wrote this piece of code to make the call and I had no problem to establish the SAP Connection (I use the SAP Logon Control OLE/COM object to do the job), and I tried to make the RFC call.
Also in this case I make the call without problems (it seems, not sure about it ...), because the RFC call returns true and no exception.
However, looking through the objReturn object/parameter, it has a value "Error 0" in it.
I was expecting a complex structure like the BAPIRETURN object in SAP or something similar if the account doesn't exist.
Tried to search with Google and SAP forums but I haven't found a real solution to my problem, so here I am to ask you all if you have some idea to solve this problem (maybe I'm only making a wrong call!!! I'm quite a newbie on SAP integration ...).
BTW, Final Notes: after a lot of RFC_NO_AUTHORIZATION on the SAP side, they gave me a SAP_ALL / S_RFC authorization (sort of, not a SAP expert) and the error RFC_NO_AUTHORIZATION disappeared, but not the Error 0 return
Dim sapConn As Object
Dim objRfcFunc As Object
Dim SAPMandante As String
Dim SAPUtente As String
Dim SAPPassword As String
Dim SAPLingua As String
Dim SAPApplicationServer As String
Dim SAPNumeroSistema As Variant
Dim SAPIDSistema As String
Dim SAPRouter As String
Dim FlagInsertLogin As Integer
Dim FlagLogin As Variant
On Error GoTo ErrorHandler
Set sapConn = CreateObject("SAP.Functions") 'Create ActiveX object
'Silent Logon
SAPMandante = "xxx"
SAPUtente = "yyyy"
SAPPassword = "zzzzzz"
SAPLingua = "IT"
SAPApplicationServer = "www.xxx.com"
SAPNumeroSistema = x
SAPIDSistema = "zzz"
SAPRouter = ""
FlagLogin = SilentLogin(sapConn, SAPMandante, SAPUtente, SAPPassword, SAPLingua, SAPApplicationServer, SAPNumeroSistema, SAPIDSistema, SAPRouter) 'IT WORKS, NO PROBLEM HERE
If FlagLogin = False Then
'Explicit Logon
If sapConn.Connection.logon(0, False) <> True Then
MsgBox "Cannot Log on to SAP", 16, "Query Interrupted"
sapConn.Connection.logoff
Set sapConn = Nothing
InsertCash = False
Exit Sub
End If
End If
'BAPI RFC Call
Set objRfcFunc = sapConn.Add("BAPI_GL_ACC_EXISTENCECHECK")
objRfcFunc.exports("COMPANYCODE") = "C100"
objRfcFunc.exports("GLACCT") = "0000000001" 'Inexistent
Rem *** BAPI CALL ***
If objRfcFunc.Call = False Then
ErrorMsg = objRfcFunc.Exception 'Message collection
MsgBox ErrorMsg, 16, "Errore"
sapConn.Connection.logoff
Exit Sub
else
Dim objReturn As Object
Set objReturn = objRfcFunc.imports("RETURN")
End If
You need to put
Dim objReturn As Object
Set objReturn = objRfcFunc.imports("RETURN")
BEFORE objRfcFunc.Call
i.e. you must state what you're importing from the function before you call it. I usually put it alongside the .exports() lines.
The problem was solved, please take a look at this thread ...
http://sap.ittoolbox.com/groups/technical-functional/sap-dev/sap-rfc-call-returns-error-in-return-parameter-from-vb-before-the-rfc-call-4894968#M4902486

Filling BAPI import table parameter in EXCEL using VBA

I have a query for me which requires to clear. I am using excel 2003. the sheet contains 12 columns. I need to do export data from excel to SAP. Before exporting I need to check if the record is exist or not, if exist then delete and insert.
I have two BAPIs for this one is import table, which needs to be filled the parameters, after filling this table the BAPI searches for the relevant records.
The list will be displayed in a table. I need to search that table with values from excel then import one field value to excel.
I write this code but, it is not working the BAPI giving Error 0.
Public Function Import_Order() As Boolean
Dim oBAPIGetOrder As Object
Dim oBAPIVariant1 As Object
Dim oBAPIVariant2 As Object
Dim oBAPIVariant3 As Object
Dim oBAPIImpOrder As Variant
Dim oBAPIRet As Boolean
Dim oDoNothing As Variant
gBAPIPlanOrder = 0
Set oBAPIGetPlOrder = sBAPIControl.Add("PLANED_GET_DET_LIST") 'BAPI
Set oBAPIVariant1 = oBAPIGetPlOrder.exports.Item("SELECTIONCRITERIA") 'Internal table
Set oBAPIVariant2 = oBAPIGetPlOrder.Tables.Item("DETAILEDLIST") 'Table
oBAPIVariant1.Value("MATERIAL") = eMaterial
oBAPIVariant1.Value("PLANT") = ePlnPlant
lBAPIRet = oBAPIGetPlOrder.call
If lBAPIRet Then
'oBAPIImpOrder = oBAPIGetPlOrder.imports.Item("PLANNEDORDER_NUM")
a = oBAPIVariant2.Rows.Count
oBAPIImpOrder = oBAPIVariant2.Value("PLANNEDORDER_NUM")
Import_PlannedOrder = True
Else
oBAPIImpOrder = 0
Import_PlannedOrder = False
End If
End Function
Thanks in advance for any help...
please place the call function statement
lBAPIRet = oBAPIGetPlOrder.call
after directly the exports statement and before the tables and importstatements

Resources