单元格中的Excel VBA文件夹路径导入数据

时间:2018-03-13 22:24:03

标签: excel-vba vba excel

我有一个从所选电子表格中提取数据的宏。我最初设置的方式是在当前文件路径位置打开。然后,用户将选择要从中复制数据的文件,然后vba执行其余操作。我想改变是因为文件路径在单元格中输入,然后打开的位置将是该文件路径。以下是我目前的代码:

With Workbooks.Open(Application.GetOpenFilename)
Sheets(1).Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows(2).Activate
Range("G24").Select
ActiveSheet.Paste
.Close False
End With

我有类似的东西,根据单元格中的文件路径打开。但我似乎无法弄清楚如何更改上面的脚本

M = Sheets("Meter Data").Range("N12")
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = M
.Show
End With

1 个答案:

答案 0 :(得分:0)

您需要获得FileDialog的调用结果并将其传递给您的打开/复制/关闭代码。

您还应该避免使用所有Select并处理一些例外情况,例如

Sub Demo()
    Dim wb As Workbook
    Dim rng As Range
    Dim wsCurrent As Worksheet
    Dim DefaultFile As String

    Set wsCurrent = ActiveSheet
    DefaultFile = ActiveWorkbook.Worksheets("Meter Data").Range("N12")
    If Dir(DefaultFile) = vbNullString Then
        MsgBox DefaultFile & vbNewLine & "does not exist." & vbNewLine & "What Now?"
    Else
        With Application.FileDialog(msoFileDialogOpen)
            .AllowMultiSelect = False
            .InitialFileName = DefaultFile
            .Show
            If .SelectedItems.Count > 0 Then
                Set wb = Workbooks.Open(.SelectedItems(1))
                With wb.Sheets(1)
                    Set rng = .Range(.Range("A1").End(xlToRight), .Range("A1").End(xlDown))
                    rng.Copy wsCurrent.Range("G24")
                    wb.Close False
                End With
            End If
        End With
    End If
End Sub