[英]How do I make a macro that enables me to import data from one workbook to another ?B
Basically I would like to import data by clicking on a button assigned with the macro which would open the file browser, prompting the user to open the excel file they would like to import. 基本上,我想通过单击分配给宏的按钮来导入数据,这将打开文件浏览器,提示用户打开他们要导入的excel文件。 I have tried to debug my codes but my For Each loop keeps getting an error, any help is appreciated!
我尝试调试代码,但是我的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
Use a variable for the workbook object: 为工作簿对象使用一个变量:
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
Remove the file path part. 删除文件路径部分。 Variety of methods available.
有多种可用的方法。 I used the one from here .
我从这里用的那个。
The Workbooks object is the collection of all the Workbook objects that are currently open in the Microsoft Excel application.
Workbooks对象是Microsoft Excel应用程序中当前打开的所有Workbook对象的集合。
It does not need the file path just the name. 它不需要文件路径,仅需要名称。 You could also have said
ActiveWorkbook
, though this would have been perhaps less robust. 您可能还说过
ActiveWorkbook
,尽管它可能不够健壮。
Edit: Or as in @TimWilliam's answer, you can store the now open workbook in a variable and use that as the reference. 编辑:或者像在@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.