检查Excel工作簿是否打开 [英] Checking if an Excel Workbook is open

查看:111
本文介绍了检查Excel工作簿是否打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以查看Excel工作簿(例如DataSheet.xls)是否处于打开状态(使用中)?如果要打开该工作簿,我想关闭它.

Is there a way to see if an Excel Workbook, say DataSheet.xls, is open (in use) or not? I would like to close that Workbook if it is opened.

推荐答案

正确的方法是检查Application.Workbooks对象.在VBA中,您应该编写:

The right way is to examine the Application.Workbooks object. In VBA you would write:

Dim wb as Workbook
On Error Resume Next                       '//this is VBA way of saying "try"'
Set wb = Application.Workbooks(wbookName)
If err.Number = 9 then                     '//this is VBA way of saying "catch"'
    'the file is not opened...'
End If

换句话说,工作簿是所有打开的工作簿的数组(或用VBA术语表示,集合).

In other words, Workbooks is an array (or in VBA terms, Collection) of all open workbooks.

在C#中,以下代码有效:

In C# the following code works:

    static bool IsOpened(string wbook)
    {
        bool isOpened = true;
        Excel.Application exApp;
        exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        try
        {
            exApp.Workbooks.get_Item(wbook);
        }
        catch (Exception)
        {
            isOpened = false;
        }
        return isOpened;
    }

您可能希望自己将引用传递给Excel.Application.

You will probably want to pass the reference to Excel.Application yourself.

这篇关于检查Excel工作簿是否打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆