有没有办法编写代码(VBA),它能够确认你在宏运行时打开一个未知的Excel文件???
我的目的是将一些值从未知Excel工作簿复制到正在运行的宏上的值,但我不确定是否可以。
代码的想法是这样的:
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
任何想法。
答案 0 :(得分:3)
我有一个更好的建议。使用Application.GetOpenFilename
让用户选择文件,然后打开该文件。这样代码就可以知道正在打开哪个文件。例如
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