GetObject有效,CreateObject不起作用

时间:2019-10-04 13:53:51

标签: excel object vbscript createobject

尝试编写一个脚本

  • 如果excel会话已经打开,请将其加入此会话,
  • Excel会话未打开,因此创建了一个。

第一个选项效果出色!第二种选择不起作用,也没有给出任何解释,只是退出而无所事事!

Dim objXLApp, objXLWb, objXLWs
Dim XLWasRunning

XLWasRunning = True

Set objXLApp = GetObject(, "Excel.Application")

If Not TypeName(objXLApp) = "Empty" Then
    strMessage = "Excel Running."
Else
    strMessage = "Excel Not Running."
    Set objXLApp = CreateObject("Excel.Application")
End If

Set objXLWb = objXLApp.Workbooks.Open("F:\GFD\Sam\Test\test.xlsx")
Set objXLWs = objXLWb.Sheets(1)

编辑:将CreateObject(, "Excel.Application")更改为CreateObject("Excel.Application")

1 个答案:

答案 0 :(得分:1)

此代码根据您收到的评论应该可以正常工作

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

    var objects: NSArray?
    Bundle.main.loadNibNamed("CellView", owner: self, topLevelObjects: &objects)

    var newView = NSView()
    for object in objects ?? [] {
        if (object is NSView) {
            newView = object as! NSView
            break;
        }
    }

    var cellView: CellView?
    for view in newView.subviews {
        print("class: \(view.className) ")
        if (view is CellView) {
            cellView = view as? CellView
            break;
        }
    }

    cellView?.imageView.image = image
    cellView?.textFieldView.stringValue = text

    return cellView
}

您可能要添加以下内容,以检查是否应该再次加载工作簿:

Dim objXLApp, objXLWb, objXLWs
Dim XLWasRunning
Dim strMessage

' Get running instance
Set objXLApp = GetObject("", "Excel.Application")

If Not objXLApp Is Nothing Then
    strMessage = "Excel Running."
    XLWasRunning = True
Else
    strMessage = "Excel Not Running."
    Set objXLApp = CreateObject("Excel.Application")
    XLWasRunning = False
End If

objXLApp.Visible = True

Set objXLWb = objXLApp.Workbooks.Open("C:\Temp\test.xlsx")
Set objXLWs = objXLWb.Sheets(1)

如果Excel已经在运行,您还可以在加载工作簿之前检查它是否已经加载:

If Not XLWasRunning Then
    Set objXLWb = objXLApp.Workbooks.Open("C:\Temp\test.xlsx")
    Set objXLWs = objXLWb.Sheets(1)
End If