我正在尝试打开 Excel 工作簿,或者如果已打开,请抓取其对象。
几乎所有在线内容都假设您正在从 Excel 运行 VBA,因此可以轻松扫描打开的工作簿以查看您的特定工作簿是否已打开。
Excel 实例可能未在我的计算机上运行。
我找到了一种方法来完成我需要的事情,除了默认情况下,它会自动隐藏我的工作簿。我可以手动取消隐藏,但我不想这样做。
我发现了以下内容
xlApp.Windows(fileName).Visible = true
如果我首先手动取消隐藏它,这会起作用。
如果我在手动取消隐藏之前尝试运行这行代码,我会得到
运行时错误:下标超出范围。
Private Type myType
fileName As String
folderPath As String
filePath As String
app As excel.Application
WB As excel.Workbook
End Type
Private this As myType
Private Sub getWorkbook()
Set this.WB = GetObject(this.filePath)
If Not this.WB Is Nothing Then
Set this.app = this.WB.Application
End If
Set this.WB = this.app.Workbooks.Open(this.filePath)
this.app.Visible = True
this.app.Windows(this.fileName).Visible = True
以下更改有效。
Private Sub getWorkbook()
Set this.WB = GetObject(this.filePath)
If Not this.WB Is Nothing Then
Set this.app = this.WB.Application
End If
Set this.WB = this.app.Workbooks.Open(this.filePath)
this.app.Windows(this.fileName).Visible = True
结束子
我删除了 this.app.visible = true ,它开始为我工作。但我不确定为什么。
我知道一些开发人员使用下面的代码来打开 Excel 文件。然而,根据我的测试,这个解决方案并不被认为是可靠的。
Set this.WB = GetObject("C:\test.xlsx")
在获取工作簿对象之前,请尝试获取
Excel Application
。
Private Type myType
fileName As String
folderPath As String
filePath As String
app As Excel.Application
WB As Excel.Workbook
End Type
Private this As myType
Private Sub getWorkbook()
this.filePath = "d:\temp\"
this.fileName = "excel_img.xlsx"
Set this.app = Nothing
On Error Resume Next
Set this.app = GetObject(, "excel.application")
On Error GoTo 0
If this.app Is Nothing Then
Set this.app = CreateObject("excel.application")
End If
this.app.Visible = True
Set this.WB = Nothing
On Error Resume Next
Set this.WB = this.app.Workbooks(this.fileName)
On Error GoTo 0
If this.WB Is Nothing Then
Set this.WB = this.app.Workbooks.Open(this.filePath & this.fileName)
End If
this.WB.Activate
this.WB.Windows(1).Visible = True
End Sub