Home » excel » Acknowledge automatically an Excel File VBA

Acknowledge automatically an Excel File VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

is there any way to write a code (VBA) that it will be able to acknowledge that you open an Unknown Excel File while the macro is running???

My purpose is to copy some values from the Unknown Excel Workbook to the one on the macro which is running, but I am not sure if that is possible.

The idea of the code would be something like that:

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

Any thoughts.

How to&Answers:

I have a better suggestion. Use the Application.GetOpenFilename to make the user select the file and then open that file. That ways the code will know which file is being opened. For example

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