VB6 检查 Excel 工作簿是否打开

VB6 Check if Excel Workbook is Open

我正在使用 VB6 开发一个项目(不,我不能迁移到 .NET),该项目涉及打开 Excel 文件并向其写入内容。

一切正常,没有太大问题,但是如果用户关闭 Excel 文件,我会收到以下错误:

Run-time error '1004'

Method 'Rows' of object '_Global' failed

此错误的代码是:

Public Sub LogValues()
    Dim rowNum As Integer
    Dim tempNum As Integer
    rowNum = sheet.Cells(Rows.Count, 1).End(xlUp).Row + 1
    tempNum = sheet.Cells(Rows.Count, 2).End(xlUp).Row + 1
    'Other stuff
End Sub

显然,错误来自 excel 工作簿被关闭并且不再存在于内存中。找到这个问题的解决方案是我目前的问题。

如何检查工作簿是否仍处于打开状态,如果未打开,请打开它?

尝试使用工作簿并在关闭时捕获错误。

sub workOnWb()

    on error goto not_open

    with workbooks("mybook1.xlsx")
        on error goto 0
        'work with it
    end with

    exit sub

    not_open:
        if err.number = 1004 then
            workbooks.open("c:\mybook1.xlsx")
            resume
        else
            debug.print err.number & ": " & err.description
        end if

end sub

您可以做的还有很多,但这涵盖了您的一般查询的基础知识。