简体   繁体   English

脚本打开多个Excel实例

[英]Script opening multiple Excel instances

I have some VBScript on a Bartender (labeling software) template that accesses an Excel spreadsheet and concatenates data for a given BOM Code in to a string on a report (all data is pulled from the same row). 我在调酒师(标签软件)模板上有一些VBScript,该模板可访问Excel电子表格并将给定BOM代码的数据连接到报表的字符串中(所有数据均从同一行提取)。 Modifying the spreadsheet or running the script via our application that integrates with Bartender causes many instances of Excel to open and immensely slows down any computer working with the template. 通过与Bartender集成的应用程序修改电子表格或运行脚本会导致许多Excel实例打开,并极大地降低了使用该模板的计算机的速度。

Public Function GetData()
    Set objExcel = CreateObject("Excel.Application")
    Set objWorkbook = objExcel.Workbooks.Open  _
        ("C:\Users\Public\Formulator\Labels\BOMSuffixes.xlsx")

    intRow = 2
    strNames = ""
    genericDescription = ""
    containerWeight = ""
    containerUom = ""

    Do Until objExcel.Cells(intRow,7).Value = ""
        strNames = objExcel.Cells(intRow, 7).Value
        If InStr(Field("BOM.BOMCode"),strNames) <> 0 Then 
            genericDescription = objExcel.Cells(intRow, 8).Value
            containerWeight = objExcel.Cells(intRow, 9).Value
            containerUom = objExcel.Cells(intRow, 10).Value
        End If

        intRow = intRow + 1
    Loop

    GetData = Field("BOM.BulkQuantity") + " " + Field("BOM.BulkUnits") +
              " (" + CStr(Round(Field("BOM.BulkQuantity")*0.453592, 2) ) +
              " Kg)" +" packed in a " + CStr(containerWeight)  + " " +
              containerUom + " (" + CStr(Round(containerWeight*0.453592, 2) ) +
              " Kg)" + ", " + genericDescription

    objExcel.Close
    objExcel.Quit
    objExcel.DisplayAlerts = False
End Function

If you want to avoid creating and destroying Excel instances over and over you could leave the instance running at the end of the script and (try to) re-attach to an already running instance at the beginning. 如果要避免一遍又一遍地创建和销毁Excel实例,可以让该实例在脚本末尾运行,并(尝试)在开始时将其重新附加到已经运行的实例。 Only create a new instance if that fails. 仅在失败时创建一个新实例。

Public Function GetData()
    On Error Resume Next
    Set objExcel = GetObject(, "Excel.Application")
    If Err Then
        If Err.Number = 429 Then
            Set objExcel = CreateObject("Excel.Application")
        Else
            WScript.Echo Err.Number & ": " & Err.Description
            WScript.Quit 1
        End If
    End If
    On Error Goto 0

    ...

    
  
 
  
  
    objExcel.Close 
  
    
  
 
  
  
    objExcel.Quit 
  
    
  
 
  
  
    objExcel.DisplayAlerts = False 
  
    Set objExcel = Nothing
End Function

Note however, that with this approach you need some kind of cleanup job to remove the orphaned Excel instance(s) at some point. 但是请注意,使用这种方法时,您需要某种清理作业才能在某个时候删除孤立的Excel实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM