自动确认Excel文件VBA

是否有任何方法来编写代码(VBA),它将能够确认您在macros运行时打开未知的Excel文件?

我的目的是将未知的Excel工作簿中的一些值复制到正在运行的macros上,但我不确定这是否可能。

代码的想法是这样的:

Sub test() MSG1 = MsgBox("Do you want to copy the values?", vbYesNo, "OPEN") If MSG1 = vbYes Then MsgBox "Open the file you want to copy" 'Here is when the user has to open the file and the VBA 'acknowledge that and keep running the macro but only if the file is open ThisWorkbook.Range("A1:B10").Value = _ Workbooks(Workbooks.Count).Range("A1:B10").Value End If End Sub 

有什么想法吗。

我有一个更好的build议。 使用Application.GetOpenFilename使用户select文件,然后打开该文件。 这种方式的代码将知道哪个文件正在打开。 例如

 Sub test() Dim Ret, msg Dim wb1 As Workbook, wb2 As Workbook msg = MsgBox("Do you want to copy the values?", vbYesNo, "OPEN") If msg = vbYes Then Set wb1 = ThisWorkbook Ret = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*") If Ret <> False Then Set wb2 = Workbooks.Open(Ret) wb1.Sheets("Sheet1").Range("A1:B10").Value = _ wb2.Sheets("Sheet1").Range("A1:B10").Value End If End If End Sub