2012-11-22 88 views
1

是否有任何方法來編寫代碼(VBA),它將能夠確認您在宏運行時打開未知Excel文件?自動確認一個Excel文件VBA

我的目的是將未知的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 

任何想法。

回答

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