简体   繁体   English

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

[英]Excel VBA Folder Path from Cell to import data

I have a macro that pulls in data from a selected spreadsheet. 我有一个宏,可从选定的电子表格中提取数据。 The way I've originally set it up is to open at the current file path location. 我最初设置的方式是在当前文件路径位置打开。 The user would then select what file to copy the data from and vba does the rest. 然后,用户将选择要从中复制数据的文件,然后vba完成其余的工作。 I would like to change is so the file path gets input in a cell and then the opened location would then be that file path. 我想更改的是文件路径在单元格中输入,然后打开的位置就是该文件路径。 Below is my current code: 下面是我当前的代码:

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

I have something like this that opens based on the file path in the cell. 我有类似的东西会根据单元格中的文件路径打开。 But I ca't seem to figure out how to change my script above 但是我似乎不知道如何在上面更改我的脚本

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

You need to get the result of the call to FileDialog and pass it into your Open/Copy/Close code. 您需要获取对FileDialog的调用结果,并将其传递到打开/复制/关闭代码中。

You should also avoid all those Select 's and handle some exceptions, something like this 您还应该避免所有这些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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM