依次打开和关闭Excel以将数据导入SAP时,循环跳过最后一行

时间:2018-10-11 20:54:00

标签: excel vbscript sap

我正在尝试使SAP中的某些每月人工销售订单自动化。它的作用是打开2个Excel工作簿并将销售信息导入SAP(事务va01)。

该脚本的工作方式如下:

  1. 打开帮助文件,将包含销售信息的地址提取到Excel文件中(在测试中,我使用3行地址/文件)
  2. 打开具有获取地址的销售信息文件(在测试中,我使用7行数据进行复制,总共8行,每个文件中包含名称行)
  3. 将销售信息导入SAP(va01交易),遍历每一行。
  4. 在帮助文件中查找下一个地址,然后重复进行直到完成,然后关闭所有内容。

问题在于,并非所有信息都复制到SAP,除最后一个销售信息文件外,所有行都跳过最后一行。

我认为销售信息文件中的行循环会跳过最后一行/在要打开另一个销售信息文件时将工作簿提前关闭,这对SAP和VBS来说是新手,找不到很好的解决方案在关闭当前打开的信息文件然后打开下一个信息文件之前,让循环完成向SAP添加信息的方法。

感谢您提供帮助/输入来解决此问题

If Not IsObject(application) Then
   Set SapGuiAuto  = GetObject("SAPGUI")
   Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
   Set connection = application.Children(0)
End If
If Not IsObject(session) Then
   Set session    = connection.Children(0)
End If
If IsObject(WScript) Then
   WScript.ConnectObject session,     "on"
   WScript.ConnectObject application, "on"
End If


Set xlapp = CreateObject("Excel.Application")

Dim xlhlpwb
Dim xlhlpsh
Dim xlwb
Dim xlsh
Dim Rw

'Adress to Help-file, open and select sheet 1
Set xlhlpwb = xlapp.Workbooks.Open("C:\tmp\help-file_test.xlsx")
Set xlhlpsh = xlhlpwb.Sheets(1)

'Loop for adresses to invoice data
for n = 1 to xlapp.ActiveCell.SpecialCells(11).Row
    m = 1 
    wbadress =  xlhlpsh.Cells(n,m).Value

'Open Workbook with invoice info and set worksheet to use, "Rw" is used in SAP to help insert the info
 Set xlwb = xlapp.Workbooks.Open("" & wbadress & "")
 Set xlsh = xlwb.Sheets(1)
 Rw = 0

'Fetch info per row in worksheet
 for i = 2 to xlapp.ActiveCell.SpecialCells(11).Row
   for j = 1 to xlapp.ActiveCell.SpecialCells(11).Column 
      if j=22 then ARTICLE =  xlsh.Cells(i,j).Value 
      if j=23 then AMOUNT =  xlsh.Cells(i,j).Value
      if j=25 then INFO =  xlsh.Cells(i,j).Value
   next

'Add info to SAP transaction (va01-"create invoice")
  session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\01/ssubSUBSCREEN_BODY:SAPMV45A:4400/subSUBSCREEN_TC:SAPMV45A:4900/tblSAPMV45ATCTRL_U_ERF_AUFTRAG/ctxtRV45A-MABNR[1,"& Rw &"]").text = ARTICLE
  session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\01/ssubSUBSCREEN_BODY:SAPMV45A:4400/subSUBSCREEN_TC:SAPMV45A:4900/tblSAPMV45ATCTRL_U_ERF_AUFTRAG/txtRV45A-KWMENG[2,"& Rw &"]").text = AMOUNT
  session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\01/ssubSUBSCREEN_BODY:SAPMV45A:4400/subSUBSCREEN_TC:SAPMV45A:4900/tblSAPMV45ATCTRL_U_ERF_AUFTRAG/txtVBKD-BSTKD[27,"& Rw &"]").text = INFO
  session.findById("wnd[0]/usr/tabsTAXI_TABSTRIP_OVERVIEW/tabpT\01/ssubSUBSCREEN_BODY:SAPMV45A:4400/subSUBSCREEN_TC:SAPMV45A:4900/subSUBSCREEN_BUTTONS:SAPMV45A:4050/btnBT_POAN").press

'To make sure the right row in SAP is selected for next row in loop
  Rw = 1

 next

 xlwb.Close True
 Set xlsh = Nothing
 Set xlwb = Nothing
next


Set xlwb = Nothing
Set xlsh = Nothing
xlhlpwb.Close True
Set xlhlpwb = Nothing
Set xlhlpsh = Nothing
xlapp.Quit
set xlapp = Nothing
Rw = 0

0 个答案:

没有答案