如何创建一个允许我将数据从一个工作簿导入另一个工作簿的宏?

时间:2018-02-07 05:47:31

标签: excel vba excel-vba

基本上我想通过点击分配了宏的按钮来导入数据,该按钮将打开文件浏览器,提示用户打开他们想要导入的excel文件。我试图调试我的代码,但我的For Each循环一直出错,任何帮助都表示赞赏!

Sub BrowseForFile()  
    Dim directory As String, fileName As String, sheet As Worksheet, total As Integer

    fileName = Application.GetOpenFilename(, , "Browse for Workbook")
    Workbooks.Open (fileName)

    For Each sheet In Workbooks(fileName).Worksheets
        total = Workbooks("FIEP.xlsm").Worksheets.count
        Workbooks(fileName).Worksheets(sheet.Name).Copy _
          after:=Workbooks("FIEP.xlsm").Worksheets(total)
    Next sheet

    Workbooks(fileName).Close
End Sub

2 个答案:

答案 0 :(得分:1)

为工作簿对象使用变量:

Sub BrowseForFile()

 Dim directory As String, fileName As String, sheet As Worksheet, total As Long
 Dim wb As Workbook

 fileName = Application.GetOpenFilename(, , "Browse for Workbook")


 Set wb = Workbooks.Open(fileName)

 For Each sheet In wb.Worksheets
    total = Workbooks("FIEP.xlsm").Worksheets.count
    sheet.Copy after:=Workbooks("FIEP.xlsm").Worksheets(total)
 Next sheet

 wb.Close

End Sub

答案 1 :(得分:0)

删除文件路径部分。有多种方法可供选择。我使用了here中的那个。

  

Workbooks对象是所有工作簿的集合   当前在Microsoft Excel应用程序中打开的对象。

它不需要文件路径只是名称。你也可以说ActiveWorkbook,虽然这可能不太健壮。

编辑:或者在@TimWilliam的回答中,您可以将现在打开的工作簿存储在变量中,并将其用作参考。

Option Explicit

Sub BrowseForFile()

    Dim directory As String, fileName As String, sheet As Worksheet, total As Integer

    fileName = Application.GetOpenFilename(, , "Browse for Workbook")

    Workbooks.Open (fileName)

    Dim fso As New FileSystemObject 'Requires references to MS Scripting Runtime

    fileName = fso.GetFileName(fileName)

    For Each sheet In Workbooks(fileName).Worksheets '
        Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("FIEP.xlsm").Worksheets(total)
    Next sheet

    Workbooks(fileName).Close

End Sub