首页 > 解决方案 > 使用 VBA 关闭从 SAP 导出的 Excel 时出现问题

问题描述

我运行一个宏,它从 SAP 下载 Excel 报告,保存它,然后我需要关闭 Excel。我在此页面中阅读了类似的帖子,但没有一个可以解决我的问题。

问题是一旦宏完成,从 SAP 下载的 excel 会自动打开。就像 Excel 在后台运行一样。所以,如果我在宏期间关闭它,代码将找不到打开的 Excel(这很有意义,因为 excel 尚未打开)并给出错误。但是当宏完成时出现 excel(那是因为 SAP 配置, 当您下载电子表格时, excel 会自动打开。我尝试更改 SAP 配置但没有幸运)

我尝试放置 Application.Wait,Workbook.Close,杀死工作簿(这会出现问题,因为弹出窗口显示 wb 不存在),调用另一个子等等。

我尝试了在此页面中阅读的解决方案,该解决方案添加了 wshell 部分,但在我的代码中不起作用

测试Excel.xlsm

        Sub test

        'Sap conection

        Application.DisplayAlerts = False
        Application.ScreenUpdating = False

        session.findById("wnd[0]").maximize
        session.findById("wnd[0]/tbar[0]/okcd").Text = "/nzv04hn"
        session.findById("wnd[0]").SendVKey 0
        session.findById("wnd[0]/usr/ctxtS_VKORG-LOW").Text = "CR01"
        session.findById("wnd[0]/usr/ctxtS_AUART-LOW").Text = "zor"
        session.findById("wnd[0]/usr/chkP_PGI").SetFocus
        session.findById("wnd[0]").SendVKey 8
        session.findById("wnd[1]/tbar[0]/btn[0]").press
        session.findById("wnd[0]").SendVKey 43
        session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "C:\Users\xxx\Desktop\"
        session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "CR01ZV04HN.XLSX"
        session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 4
        session.findById("wnd[1]/tbar[0]/btn[7]").press

        Application.DisplayAlerts = True
        Application.ScreenUpdating = True

        Set Wshell = CreateObject("WScript.Shell")
        Wshell.Run "C:\Users\Desktop\xxx\SAP_Workbook_Close.vbs", 1, False
        End sub

SAP_Workbook_Close.vbs

SAP_Workbook = "CR01ZV04HN.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

在此先感谢您的帮助。

标签: excelvbasap

解决方案


推荐阅读