Private Sub CommandButton1_Click()
Unload LOGINZGLOC
Dim strPath As String
strPath = Environ("USERPROFILE") & "\Desktop\saplgpad.lnk"
Shell "strPath", 4
Set WshShell = CreateObject("WScript.Shell")
Do Until WshShell.AppActivate("SAP Logon Pad")
Application.Wait Now + TimeValue("0:00:01")
Loop
Dim Row
Dim UD As Worksheet
Set UD = Application.ActiveSheet
Row = 3
Set SapGui = GetObject("SAPGUI")
Set Appl = SapGui.GetScriptingEngine
Set Connection = Appl.Openconnection("[GT] ECC Production (GE4)", True)
Set session = Connection.Children(0)
This is the code I use for opening SAP using login info got from a userform. But since this is a code that's meant to be used by several employees and working colleagues, I need to open SAP on any user profile, for that I tried creating a shortcut and referencing to him on Desktop, since I'm new to VBA the code might look a little raw. The code fails, saying that the file couldn't be found.
Related
I have this sub that are calling for execute other two subs in the program, but when I try to execute it pops up the Compilation error: syntax error right on the fisrt line of the sub.
Sub MacroPrimaria()
Call SAPOpenSessionFromLogon
Application.Wait Now + TimeValue("00:00:05")
Call executarsap
MsgBox ("PROCESSAMENTO FINALIZADO")
End Sub
Sub SAPOpenSessionFromLogon()
Dim SapGui
Dim Applic
Dim connection
Dim session
Dim WSHShell
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", vbNormalFocus
Set WSHShell = CreateObject("WScript.Shell")
Do Until WSHShell.AppActivate("SAP Logon ")
Application.Wait Now + TimeValue("0:00:01")
Loop
Set WSHShell = Nothing
Set SapGui = GetObject("SAPGUI")
Set Applic = SapGui.GetScriptingEngine
Set connection = Applic.OpenConnection("S/4 HANA - PRODUÇÃO", True)
Set session = connection.Children(0)
session.findById("wnd[0]").maximize
End Sub
Sub executarsap()
Dim Application, SapGuiAuto, connection, session, WScrip
'**IMPORTANTE**: Abaixo daqui, basta colar o scrip gerado pela gravação do SAP, sem retirar nada:
'This sub it's okay and has confidential stuff so its just to know.
End Sub
I'm gettin stuck with this error on the lines:
"Sub MacroPrimaria()"
"Sub SAPOpenSessionFromLogon()"
I'm expecting to get able to execute the macro
Your code isn't giving a compile error for me.
This is the code I use to interact with SAP and it hasn't given me any problems so far (can't remember where I found it on the Internet though).
It may help.
Public Sub Execute_SAP()
'Login details here.
Dim LogInDetail As Variant
LogInDetail = Array("***YOUR USER NAME***", "***YOUR PASSWORD***")
'Open the SAP Log-In screen and wait for it to load.
Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", 4
Dim WshShell As Object
Set WshShell = CreateObject("WScript.Shell")
Do Until WshShell.AppActivate("SAP Logon ")
Application.Wait Now + TimeValue("0:00:01")
Loop
Set WshShell = Nothing
Dim SAPGui As Object
Set SAPGui = GetObject("SAPGUI")
Dim Appl As Object
Set Appl = SAPGui.GetScriptingEngine
Dim Connection As Object
Set Connection = Appl.OpenConnection("S/4 HANA - PRODUÇÃO", True)
Dim Session As Object
Set Session = Connection.Children(0)
With Session
'Log-in to the session.
.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "300"
'The next two lines accept the username and password - LogInDetail variant holds those two values.
.findById("wnd[0]/usr/txtRSYST-BNAME").Text = LogInDetail(0)
.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = LogInDetail(1)
.findById("wnd[0]/usr/txtRSYST-LANGU").Text = "EN"
.findById("wnd[0]").maximize
.findById("wnd[0]").SendVKey 0 'ENTER
'Rest of SAP code - each line starts with
' .findById("wnd[0]
'Use SAPs macro recorder to get the detail... is probably what you've got in executearsap()
End With
End Sub
thanks for the help!!
Apparently the file that I created the script was corrupted, when I create a new file the code runs properly.
I am working on an application that stores it's files in the Documents folder to easily sync with One Drive. I need to make them available offline, in case of an outage. I have changed the settings so that I have a local copy. When I click directly on the Excel file in File Explorer, the program opens it with no problem. However, when I try to open the file in my application, I get an error stating "No network found..." etc. Is there another way to do this? Thanks in advance.
Public Sub LoadMemberList()
lstMemberList.Clear()
Dim mMember As Members
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim range As Excel.Range
xlApp = New Excel.Application
xlBook = xlApp.Workbooks.Open(CurrentYearPath) '***This is where the exception is thrown.
xlSheet = xlBook.Worksheets("sheet1")
range = xlSheet.UsedRange
Dim rs As Object(,) = CType(range.Value, Object(,))
Dim records As Long = rs.GetUpperBound(0)
If records > 1 Then
For x = 2 To records
mMember.MemberNumber = FormatNumber(rs(x, 1))
mMember.MemberName = rs(x, 4) + " " + rs(x, 3)
lstMemberList.Add(mMember)
Next
End If
xlBook.Close()
xlApp.Quit()
KillExcel()
xlApp = Nothing
xlBook = Nothing
xlSheet = Nothing
range = Nothing
End Sub
Public Function CurrentYearPath() As String
Dim CurrentYear As Integer
CurrentYear = CInt(Format(Now, "yyyy"))
Return My.Computer.FileSystem.SpecialDirectories.MyDocuments + "\DailyBook\Rosters\Membership" + CurrentYear.ToString + ".xlsx"
End Function
Scroll down here
https://learn.microsoft.com/en-us/onedrive/plan-onedrive-enterprise#key-onedrive-features
and you'll find this,
However, if you plan to access a file while disconnected from the internet, you can make the file available offline by right-clicking it, and then selecting Always keep on this device.
I have a macro to download certain SAP reports to Excel. My issue is that if I run the macro more than once in the same SAP session (first time it works fine), I get a Run time error 619 which I am not able to bypass.
For some reason (I think it's related to which server the user is logged on to), the SAP module (RE-FX) have two different variants/GUIs. Therefore, I have two different setups for downloading the report to Excel depending on the variant/GUI.
I am using the On Error Goto statement to shift between those two variants. The Run time error appears in the line following the On Error Goto statement.
As mentioned, this works fine the first time I run the macro (no Run Time error occurs and the macro jumps to the error handler as expected), but the second time I run it, the error '619' appears and it is not possible to bypass it.
I have tried the solution in this post (including Application.Wait):
Cannot Bypass Error 619 [executing SAP from VBA]
But that did not fix it (it is not the timing which is the issue here).
Sub Run_REISCDCF()
Dim Filepath As String
Dim ReportDate As String
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Filepath = ThisWorkbook.Sheets("Guide").Cells(5, 5).Text 'place to store SAP reports
'Create connection to SAP
'------------------------------------------
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children(0)
'------------------------------------------
'Removed some code to run the report and change layout (which works fine)
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
On Error GoTo XLSX_variant 'SAP has two different GUI's for RE-FX with one of them only allowing to download to a MHTML file type
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath" '<-- At this line the Run Time error appears
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
XLSX_variant:
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath"
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.XLSX"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Try this...
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
End If
This code will lookup for the button in the session you are and if it finds it it will click on it else it means it’s not there and I’ll continue with next line.
Sub Run_REISCDCF()
Dim Filepath As String
Dim ReportDate As String
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Filepath = ThisWorkbook.Sheets("Guide").Cells(5, 5).Text 'place to store SAP reports
'Create connection to SAP
'------------------------------------------
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children(0)
'------------------------------------------
'Removed some code to run the report and change layout (which works fine)
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
'SAP has two different GUI's for RE-FX with one of them only allowing to download to a MHTML file type
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
End If
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath" '<-- At this line the Run Time error appears
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Thanks to #reFractil for coming up with a solution that worked!
I had to edit his solution slightly in order to embed the two variants (download SAP report as .XLSX or .MHTML), but the structure and code proposed by reFractil is the same:
'Changed code only below
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
'Solution:
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Filepath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.XLSX" 'Download as .XLSX if in "XLSX SAP_variant"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
End If
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Filepath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML" 'Download as .MHTML if in "MHTML SAP_variant"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Apologies in advance for the length of this post, but I wanted to describe my issues in detail in the hopes one of you VBA masters can assist
Goal
Loop through all PDFs in a folder
For each PDF:select all/copy/paste into Excel
Call a separate macro to convert the pasted data into something
legible.
Background
The below sub [CopyPDFtoExcel()] worked yesterday but is now failing on the ActiveSheet.Paste line with the
"Runtime error '1004' Paste method of Worksheet class failed".
If I step though (via F8), it appears to NOT be actually opening the PDF, and therefor is unable to select all/copy/paste, producing the Runtime error. However, I do not get an error dialog, which I would think I would get (from the Debug.Assert False) if it can't find the file.
My fName's are defined as variable via a named range called path2008. These file paths were derived by running PullFilePathsforPDFs(), which spits out the full file path for each PDF in my folder. Then, I have selected those file paths and given it a name, in this case path2008, which is for 13 different PDFs. NOTE: There are actually 250+ PDFs in this folder but I selected a subset for testing, hence the 13 associated with path2008.
What I have done so far
Tested the file path for each PDF in the path2008 range by using the
(cumbersome non-looping) ActiveWorkbook.FollowHyperlink method,
which successfully opens all the PDFs. So, I'm pretty confident the
file paths are correct.
'ActiveWorkbook.FollowHyperlink "file path here"
Stripped out the select all/copy/paste VBA code, leaving just the
loop [See the sub TroubleshootingOpeningPDFLoop()]. When I step
through the FIRST time the yellow line goes from the Set oPDDoc =
oAVDoc.GetPDDoc line to the End If....presumabley meaning it found a
file during the first loop (though I do not see the PDF open). On
the SECOND (and all subsequent loops) it goes to Else then
Debug.Assert False (but no error dialog appears).
Restarted Excel and Acrobat, same issue
Restarted computer, same issue
Recreated a new workbook, same issue
Main code
Sub CopyPDFtoExcel()
Dim fName As Variant
Dim wbPayroll As Excel.Workbook
Dim wsConvert As Excel.Worksheet
Dim oPDFApp As AcroApp
Dim oAVDoc As AcroAVDoc
Dim oPDDoc As AcroPDDoc
Set wbPayroll = Workbooks("Payroll.xlsm")
Set wsConvert= wbPayroll.Sheets("Convert")
Set oPDFApp = CreateObject("AcroExch.App")
Set oAVDoc = CreateObject("AcroExch.AVDoc")
Set oPDDoc = CreateObject("AcroExch.PDDoc")
'Open the PDF file. The AcroAVDoc.Open function returns a true/false
For Each fName In Range("path2008")
If oAVDoc.Open(fName.Text, "") = True Then
Set oPDDoc = oAVDoc.GetPDDoc
Else
Debug.Assert False
End If
'Copy all using Acrobat menu
oPDFApp.MenuItemExecute ("SelectAll")
oPDFApp.MenuItemExecute ("Copy")
'Paste into Convert sheet
wbPayroll.Activate
wsConvert.Cells(1, 1).Select
ActiveSheet.Paste 'It worked yesterday, but now error on this line with below error
'Runtime error '1004' Paste method of Worksheet class failed
oAVDoc.Close (1) '(1)=Do not save changes
'oPDDoc.Close
Call ConversionMacro
Next
'Clean up
Set wbTransfer = Nothing
Set wsNew = Nothing
Set oPDFApp = Nothing
Set oAVDoc = Nothing
Set oPDDoc = Nothing
End Sub
My effort to isolate the PDF open failure problem
Sub TroubleshootingOpeningPDFLoop()
Dim fName As Variant
Dim wbPayroll As Excel.Workbook
Dim wsConvert As Excel.Worksheet
Dim oPDFApp As AcroApp
Dim oAVDoc As AcroAVDoc
Dim oPDDoc As AcroPDDoc
'Define your spreadsheet
Set wbPayroll = Workbooks("Payroll.xlsm")
Set wsConvert= wbPayroll.Sheets("Convert")
'Instantiate Acrobat Objects
Set oPDFApp = CreateObject("AcroExch.App")
Set oAVDoc = CreateObject("AcroExch.AVDoc")
Set oPDDoc = CreateObject("AcroExch.PDDoc")
'Open the PDF file. The AcroAVDoc.Open function returns a true/false
For Each fName In Range("path2008")
If oAVDoc.Open(fName.Text, "") = True Then
Set oPDDoc = oAVDoc.GetPDDoc
Else
Debug.Assert False
End If
Next
End Sub
Sub used to pull the file paths
Sub PullFilePathsforPDFs()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("D:\Stuff\MoreStuff") 'all PDFs I need are stored here
i = 1
For Each objFile In objFolder.Files
Cells(i + 1, 1) = objFile.Name
Cells(i + 1, 2) = objFile.Path
i = i + 1
Next objFile
End Sub
I am having cut/copy - paste troubles lately (runtime error 1004)
Using the latest Excel but also working on "ancient" applications.
What did the trick for me was working with the original "given" name
(Sheet1,Sheet2 etc. As soon as I added/renamed the same sheets, the runtime errors came back.
If you want to make sure to generate an error when the opening operation does not succeed, I would add the following at the end of TroubleshootingOpeningPDFLoop:
If oPDDoc is nothing then
Debug.Assert False
End If
If this doesn't return an error, that means that the file is open in the application, but that it is not visible. It could be caused by the fact that you are using a PDDoc instead of an AVDoc. So, switching the 2 might allow you to see it when debugging.
As of your main problem, it might be due to the fact that Acrobat does not process the commands fast enough and you need to include some waiting time in your code to let Acrobat enough time to process the command. For example, you could have:
'Copy all using Acrobat menu
oPDFApp.MenuItemExecute ("SelectAll")
Application.Wait TimeSerial(Hour(Now()), Minute(Now()), Second(Now()) + 1)
oPDFApp.MenuItemExecute ("Copy")
Which will make VBA wait one second before running the next command.
I have this code I wrote in VBScript for wincc, and after running it the Excel application is still running, and the project is not working properly after this script. What can I do to close the Excel app?
Here is the script:
Dim fso
Dim rowcount
Dim ExcelObject
Dim WorkbookObject
Dim file
Dim i
Dim tg
Dim objSheet1
Dim objSheet2
'Set Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ExcelObject = CreateObject("Excel.Application")
file="C:\Parametri\Codificari.xls"
Set WorkbookObject = ExcelObject.Workbooks.Open(file)
'Set objSheet1 = WorkbookObject.Worksheets(1)
Set objSheet2 = WorkbookObject.Worksheets(2)
objSheet2.Cells(1,1)=SmartTags("locatie_defect")
If (fso.FileExists(file)) Then
'Raw numbering in Excel
rowcount = objSheet2.UsedRange.Rows.count
For i=3 To rowcount
tg="defect_"&i-2
SmartTags(tg)=objSheet2.Cells(i,2)
Next
End If
On Error Resume Next
'Save and close excel
ExcelObject.DisplayAlerts = False
ExcelObject.Workbooks.Close False
ExcelObject.Workbooks.Save
ExcelObject.Quit
On Error Resume Next
The standard way to close (sans error handling)
WorkbookObject.Save
WorkbookObject.Close False
ExcelObject.Quit
Set WorkbookObject= Nothing
Set ExcelObject = Nothing
Ensure all references are fully qualified, see here. On a quick look-over this doesnt jump out from your code.
For some reason Excel doesn't follow COM rules when used as an app object. No doubt for some compatibility reason.
It does follow COM rules as a doc object.
So Set WorkbookObject = GetObject("C:\Parametri\Codificari.xls") and now when it goes out of scope it will close as long as it's not visible. So just save it and it will close when your script ends. You probably only need half the lines you have.