2

I have some VBA code that exports SAP data to a .XLSX file, then imports this file into excel. After the file is imported, I have code that performs many other actions (eg parses and organizes data, counts cells, etc). After the macro finishes, the exported SAP .XLSX file opens up and I'd like it not to.

I've tried using the Kill function, which it does successfully, but at the end of the macro, instead of opening the file, it has a message about the file not found, which makes sense.

I've tried closing the file before the macro completes, but this also results in error since the file isn't actually open.

I've tried opening and then closing the file before the macro completes, it does this successfully, but then again at the end of the macro, the file opens.

BUT, when I break the code and step through, then the file does not open at the end.

I've tried a few other various timer functions, DoEvents, and such, and still no luck.

Does anyone have any ideas on how to either: 1. Prevent the exported file from opening at the end of the code or 2. Prevent the "file not found" message from showing up so the file can be killed during the macro.

Sample code

'Opens SAP connection
Dim SAPGUI
Dim Applic
Dim connection
Dim Session
Dim WSHShell

Application.DisplayAlerts = False

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("04. R3 PRD []", True)
Set Session = connection.Children(0)
'  Session.findById("wnd[0]").iconify
  Session.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "100"
  Session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = Environ("Username")
  Session.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = sysstart.psswrd
  Session.findById("wnd[0]").sendVKey 0

Session.findById("wnd[0]").maximize
Session.findById("wnd[0]/tbar[0]/okcd").Text = "/nZUI_SELECTION"
Session.findById("wnd[0]").sendVKey 0

''Performs some filters and opens data 

' Export from SAP to .xlsx file.
Session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
Session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&XXL"
Session.findById("wnd[1]/tbar[0]/btn[0]").press
Session.findById("wnd[1]/usr/ctxt[0]").Text = "C:\Users\" & Environ("Username") & "\Downloads"
Session.findById("wnd[1]/usr/ctxt[1]").Text = "SAP_export.XLSX"
Session.findById("wnd[1]/tbar[0]/btn[11]").press

'Closes SAP connection
Set Session = Nothing
  connection.CloseSession ("ses[0]")
Set connection = Nothing


'Clear table from SMS Input
    ThisWorkbook.Worksheets("SMS Input").Select
    Cells.Select
    Selection.ClearContents

'Insert .xlsx file data
    Cells.Select
    Selection.Delete Shift:=xlUp
    Range("A6").Select
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
        "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;Password="""";User ID=Admin;Data Source=C:\Users\" & Environ("Username") & "\Downloads\SAP_export.XLSX;Mode=Share Deny None" _
        , _
        ";Extended Properties=""HDR=YES;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OL" _
        , _
        "EDB:Engine Type=37;Jet OLEDB:Database Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Je" _
        , _
        "t OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Lo" _
        , _
        "cale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Je" _
        , "t OLEDB:Bypass UserInfo Validation=False"), Destination:=Range("$A$6")). _
        QueryTable
        .CommandType = xlCmdTable
        .CommandText = Array("Sheet1$")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .SourceDataFile = "C:\Users\" & Environ("Username") & "\Downloads\SAP_export.XLSX"
        .ListObject.DisplayName = "Table_export3"
        .Refresh BackgroundQuery:=False
        .MaintainConnection = False
    End With

After the file is imported, I parse through some columns and organize the information across the worksheets.

At the end of the code, I have tried different variations as mentioned above.

'Open the export and then close to avoid it opening at end of macro.
Workbooks.Open Filename:="C:\Users\" & Environ("Username") & _
                          "\Downloads\SAP_export.XLSX"
Workbooks("SAP_export.XLSX").Close savechanges:=False
Application.Wait Now + TimeValue("0:00:01")
Kill "C:\Users\" & Environ("Username") & "\Downloads\SAP_export.XLSX"

At first, I thought this was an issue with the section where it imports the .XLSX using OLEDB but it isn't. If I End the code after the SAP connection close, the file will automatically open at the end. I've seen other posts with this same issue but no solid answers. Hopefully this is clear...

Thanks in advance for any feedback,

5
  • "I have some VBA code" if you have code which is doing something you don't want, it might be useful to share the [relevant parts of] that code. Don't ask us to guess what you're doing. Nov 21, 2016 at 22:05
  • Hi Tim, sorry about that. I added some relevant code to help clarify. It seems like it is an automatic function to open the exported .XLSX file from SAP, but not until the macro completes. This is what I am trying to figure out and prevent from happening. Thanks!
    – jmeddy
    Nov 21, 2016 at 22:32
  • Hi, I do a few things importing data from SAP. I have split mine out to multiple functions and subroutines. That said my process has been successful in exporting a file from SAP then importing the file data and then killing the file, I could close but it is only a temp file in my case. Maybe just surround your problem section with On Error Resume Next and On Error Goto 0. I don't have an issue with file opening or errors, even with out the on error code. Is it possible that something in the original sheet is referencing something in the SAP export? Try stepping through and see how you go. Nov 21, 2016 at 23:11
  • Thanks Cap'n Grumpy. What file type do you use to export the SAP info? I have several macros that use a .txt file to export and do not have this issue. For this macro, I need to use the .XLSX format because it helps a lot with formatting. I stepped through at the point where the .XLSX is exported to Excel and I can see a new VBAProject instance open for the exported file, but it does not open until the macro completes, and I am not able to close that instance for some reason. I can kill it, but then the message pops up after the macro completes.
    – jmeddy
    Nov 22, 2016 at 0:27
  • I mostly use tab separate as they are easier to import for what I want. Why don't you look at splitting your code then. Take out the open and import into a separate function with the filename as an argument. Then close it in the function and kill it back in the original sub. Nov 22, 2016 at 0:41

6 Answers 6

2

Further Suggestion:

At the end of your VBA program (without changes) , run the script below.

For example:

. . .
'Open the export and then close to avoid it opening at end of macro.
set Wshell = CreateObject("WScript.Shell")
Wshell.run "c:\tmp\SAP_Workbook_Close.vbs",1,false
End Sub

SAP_Workbook_Close.vbs:

SAP_Workbook = "SAP_export.xlsx" 
on error resume next
do
 err.clear
 Set xclApp = GetObject(, "Excel.Application")
 If Err.Number = 0 Then exit do
 'msgbox "Wait for Excel session"
 wscript.sleep 2000
 loop

do 
 err.clear
 Set xclwbk = xclApp.Workbooks.Item(SAP_Workbook)
 If Err.Number = 0 Then exit do
 'msgbox "Wait for SAP workbook"
 wscript.sleep 2000
loop

on error goto 0 
Set xclSheet = xclwbk.Worksheets(1)

xclApp.Visible = True
xclapp.DisplayAlerts = false

xclapp.ActiveWorkbook.Close


Set xclwbk = Nothing
Set xclsheet = Nothing
'xclapp.Quit
set xclapp = Nothing

Regards, ScriptMan

1
  • Hey hey, just tried it out - it works! There is a momentary flash of it at the end of the macro. But at least it just goes away so not to confuse the user.. I'm assuming the vbs can be modified to handle multiple exported worksheets if need be? Also wanted to thank you in general bc I have found a lot of useful information you've submitted on VBA/SAP issues
    – jmeddy
    Nov 24, 2016 at 4:14
2

My solution here if anybody still needs help. I created a sub in order to kill a lot of files i export. thx scriptman ...

    .findById("wnd[0]/mbar/menu[0]/menu[10]/menu[3]/menu[1]").Select
    .findById("wnd[1]/usr/ctxtDY_PATH").Text = "C:\Informe\"
    .findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "tcurr.xlsx"
    .findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 10
    .findById("wnd[1]/tbar[0]/btn[11]").press
    End With

    'Application.Wait Now + TimeValue("00:00:02")

    Call Esperar("tcurr.XLSX")

   Public Sub Esperar(Optional ByVal archivo As String)    
   On Error Resume Next    
   Set Wshell = CreateObject("WScript.Shell")    
   Do    
    Err.Clear
    Set xclapp = GetObject(, "Excel.Application")
    If Err.Number = 0 Then Exit Do
    DoEvents '---> This do the trick in VB7
    'msgbox "Wait for Excel session"

    wscript.Sleep 2000
    Loop

   Do
    Err.Clear
    Set xclwbk = xclapp.Workbooks.Item(archivo)
    If Err.Number = 0 Then Exit Do
    DoEvents
    'msgbox "Wait for SAP workbook"
    wscript.Sleep 2000    Loop

   On Error GoTo 0    
   Set xclsheet = xclwbk.Worksheets(1)

   xclapp.Visible = True
   xclapp.DisplayAlerts = False

   xclapp.ActiveWorkbook.Close

   Set xclwbk = Nothing    
   Set xclsheet = Nothing
   End Sub
1

Today I saw another solution to the problem. I really wanted to share it with you.

for example:

...
' Export from SAP to .xlsx file.
Session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
Session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&XXL"
Session.findById("wnd[1]/tbar[0]/btn[0]").press
Session.findById("wnd[1]/usr/ctxt[0]").Text = "C:\tmp"
Session.findById("wnd[1]/usr/ctxt[1]").Text = "SAP_export.XLSX"
Session.findById("wnd[1]/tbar[0]/btn[11]").press


Dim xlApp As Object
Application.Wait Now + TimeSerial(0, 0, 5)

Set xlApp = GetObject("c:\tmp\SAP_export.XLSX").Application

xlApp.Workbooks(1).Close False
'xlApp.Quit
...

Regards, ScriptMan

0

I have tried to do what I explained in the comments. It isn't very neat and I wasn't able to test. I only changed a couple of lines to tidy a couple of things up, I dont think that line is needed in the Insert .xlsx from file data section thought. Let me know how you go.

Sub OriginalSub()
  'Opens SAP connection
  [snip as no change]

  'Closes SAP connection
  [snip as no change]

  Call ImportData()

  Kill "C:\Users\" & Environ("Username") & "\Downloads\SAP_export.XLSX"

End Sub


Sub ImportData()

'Clear table from SMS Input
    ThisWorkbook.Worksheets("SMS Input").Cells.ClearContents

'Insert .xlsx file data
    ThisWorkbook.Worksheets("SMS Input").Range("A6").Select
    [snip as no changes from here by me]

    Workbooks("SAP_export.XLSX").Close savechanges:=False

End Sub
3
  • This is very similar to the way I actually have it. I have one main Sub that calls ~ 30 other subs. I have tried placing the Workbook("SAP_export.XLSX").close in different locations and subs to see if it would help. It still returns a "Subscript out range" because the file isn't actually open yet. It doesn't open until the runtime completes. The file only appears if I run the code without breaking it. If I do break, the file doesn't open at the end. I tried wait times, even using Ontime events to try to someho w programmatically break the runtime, then restart - still no luck.
    – jmeddy
    Nov 22, 2016 at 2:31
  • Are you closing your OLEDB connection and recordset? I cant say I am sure they need closing with your code the way it is, but it seems like something is holding the connection and causing the issues. If you try doing the same thing without the OLEDB import (comment it out) does it work. If so, at least you know where the issue is and then maybe restructure/customise the OLEDB import. Nov 22, 2016 at 3:40
  • Yeah, I close the OLEDB connection using .MaintainConnection = False. I tried using a .htm SAP export (which also preserves the formatting that I need) and it does not have the issue of opening up at the end of the macro. I only see this happen for excel exports from SAP.
    – jmeddy
    Nov 22, 2016 at 16:19
0

I am trying to write a little more today so that my answer will not be deleted. ;-)

I offer the following workaround for the issue:

'old codes
. . .
Session.findById("wnd[1]/usr/ctxt[1]").Text = "SAP_export.XLSX"
Session.findById("wnd[1]/tbar[0]/btn[11]").press
'new codes
SAP_Workbook = "SAP_export.xlsx" 
on error resume next
do
 err.clear
 Set xclApp = GetObject(, "Excel.Application")
 If Err.Number = 0 Then exit do
 'msgbox "Wait for Excel session"
 wscript.sleep 2000
 session.findById("wnd[0]").iconify
 session.findById("wnd[0]").maximize
loop

do 
 err.clear
 Set xclwbk = xclApp.Workbooks.Item(SAP_Workbook)
 If Err.Number = 0 Then exit do
 'msgbox "Wait for SAP workbook"
 wscript.sleep 2000
loop

on error goto 0 
Set xclSheet = xclwbk.Worksheets(1)

xclApp.Visible = True
xclapp.DisplayAlerts = false

xclapp.ActiveWorkbook.Close


Set xclwbk = Nothing
Set xclsheet = Nothing
xclapp.Quit
set xclapp = Nothing

'old codes
'Closes SAP connection
Set Session = Nothing
connection.CloseSession ("ses[0]")
Set connection = Nothing
. . . 

Regards, ScriptMan

7
  • Thank ScriptMan, I tried running the code you provided but unfortunately it enters a continuous loop at: do err.clear Set xclwbk = xclApp.Workbooks.Item(SAP_Workbook) If Err.Number = 0 Then exit do 'msgbox "Wait for SAP workbook" wscript.sleep 2000 loop
    – jmeddy
    Nov 22, 2016 at 16:06
  • I actually tried using a .htm export from SAP and then imported into Excel via web query, which solves the issue, but brings another I need to figure out. I need to find a way to clear the table query so the rest of my code works with the imported data... Guess this would be a different inquiry? I would still like to solve the .XLSX export issue so if you have further suggestion, i will try. Thanks!
    – jmeddy
    Nov 22, 2016 at 16:12
  • This means the first loop (wait for Excel) has been completed. Now you should see how looks the Excel folder. Or you can present a screenshot of the place where it does not go. ow you should see how the Excel folder looks.
    – ScriptMan
    Nov 22, 2016 at 18:14
  • So the Err.Number after Set xclwbk = xclapp.Workbooks.Item(SAP_Workbook) is equal to 9. If I comment out the On Error Resume Next, it errors out on Set xclwbk = xclapp.Workbooks.Item(SAP_Workbook) for Subscript out of Range.
    – jmeddy
    Nov 22, 2016 at 19:23
  • The variable SAP_Workbook has the value SAP_export.xlsx. What name is displayed on the screen in Excel?
    – ScriptMan
    Nov 22, 2016 at 20:05
0

So I have been reading a lot about this issue and a lot of people wondering why... i finally got to the point!! Is a thing in SAP Configuration. Go Check on top right corner... click on the TV > Settings > Interactive > Quick Info and use accesibility mode. There it is! Set it to None! and you are done... I got this from a user that told me that a lot of books opened at the end.

I wrote a small program to solved this issue, if anybody check on this let me know:

   Public Sub ConfSAP()

   Set objShell = CreateObject("WScript.Shell")

   reg = "REG_DWORD"



    strRoot_16 = "HKEY_CURRENT_USER\SOFTWARE\SAP\SAPGUI Front\SAP Frontend Server\Customize\BubbleDelay"
strRoot_17 = "HKEY_CURRENT_USER\SOFTWARE\SAP\General\AccMode"
            strModify = objShell.RegWrite(strRoot_16, "00000003", reg)
   strModify = objShell.RegWrite(strRoot_17, "On", "REG_SZ")
                strModify = Null
                strRoot_16 = Null

strRoot_17 = Null

    subfolder = Null 
    reg = Null Set 
    objShell = Nothing 
    End Sub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.