使用" GetOneFile"时返回文件名Excel宏

时间:2015-04-30 11:13:02

标签: excel-vba vba excel

在Excel中,我希望能够点击一个按钮,打开另一个Excel文件,然后在选择要打开的文件时,我希望文件名能够返回到原始Excel文件中的单元格。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您只需要在打开第二个文件之前存储结果

Sub StoreTheResultFirst()
    Dim FileSpec As String, NameOnly As String

    FileSpec = Application.GetOpenFilename()
    Range("A1").Value = FileSpec

    ary = Split(FileSpec, "\")
    NameOnly = ary(UBound(ary))
    Range("A2").Value = NameOnly

    Workbooks.Open Filename:=FileSpec
End Sub

修改#1:

这是必要的错误陷阱:

Sub StoreTheResultFirst2()
    Dim FileSpec As String, NameOnly As String

    FileSpec = Application.GetOpenFilename()
    If FileSpec = "False" Then
        MsgBox "User Cancelled"
        Exit Sub
    End If
    Range("A1").Value = FileSpec

    ary = Split(FileSpec, "\")
    NameOnly = ary(UBound(ary))
    Range("A2").Value = NameOnly

    Workbooks.Open Filename:=FileSpec
End Sub