Excel VBA - GetObject(),打开只读(已打开的文档)

时间:2014-03-05 17:08:40

标签: excel vba excel-vba

我正在尝试使用excel VBA打开另一个excel文档来提取数据 我希望能够打开并从其他用户已经打开的文档中提取数据 如何使用GetObject函数以只读参数打开文件?

2 个答案:

答案 0 :(得分:2)

使用Workbooks.Open方法并指定ReadOnly设置为true的完整路径名:

    Workbooks.Open(FileName:="C:\Users\User\Desktop\excelworkbook.xlsm", ReadOnly:=True)

假设工作簿已经打开,它将以只读方式打开。从此只读工作簿中选择所有单元格,将所有单元格复制并粘贴到其他工作簿中。

以下是代码:

    'Hide Prompts and Screen Updating (so can rename workbooks without prompts)
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

        'Create Two WorkBook Objects
        Dim Wb1 As Workbook, Wb2 As Workbook

        'Create a new workbook to copy to
        Set Wb1 = Application.Workbooks.Add()
        Wb1.SaveAs ("WorkBookToCopyTo")

        'Open the other workbook (will open as read-only because it's already open)
        Set Wb2 = Workbooks.Open(FileName:="C:\Users\User\Desktop\excelworkbook.xlsm", ReadOnly:=True)

        'activate read-only workbook, select all cells, copy
        Wb2.Activate
        Wb2.Worksheets(1).Select

        Cells.Select
        Selection.Copy

        'activate other workbook, select all cells, paste
        Wb1.Activate
        Wb1.Worksheets(1).Select

        Cells.Select
        ActiveSheet.Paste

    'Show Prompts Again
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

答案 1 :(得分:1)

您可以使用以下代码激活只读工作簿:

Workbooks.Open Filename:=file-path, ReadOnly:=True