1

有什么方法可以编写代码(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

有什么想法吗。

4

1 回答 1

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
于 2012-11-22T13:42:32.373 回答