Excel VBA - GetObject(),以只读方式打开(已打开文档)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22204446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA - GetObject(), Open read-only (already open docs)
提问by agent provocateur
I am trying to use excel VBA to open another excel document to pull data.
I would like to be able to open and pull data from documents that are already open by other users.
How can I get GetObject function to open the file with read-only parameters?
我正在尝试使用 excel VBA 打开另一个 excel 文档来提取数据。
我希望能够从其他用户已经打开的文档中打开和提取数据。
如何获得 GetObject 函数以使用只读参数打开文件?
回答by Brock Gion
Use Workbooks.Open
method and specify the full path name with ReadOnly set to true:
使用Workbooks.Open
方法并指定完整路径名并将 ReadOnly 设置为 true:
Workbooks.Open(FileName:="C:\Users\User\Desktop\excelworkbook.xlsm", ReadOnly:=True)
Assuming that workbook is already open, it will open as read-only. Select all the cells from this read-only workbook, copy, and paste everything into your other workbook.
假设工作簿已经打开,它将以只读方式打开。选择此只读工作簿中的所有单元格,将所有内容复制并粘贴到其他工作簿中。
Here is the code:
这是代码:
'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
回答by Rich
You can activate read only workbooks with the following code:
您可以使用以下代码激活只读工作簿:
Workbooks.Open Filename:=file-path, ReadOnly:=True