Excel VBA将各种excel文件导入到主表

时间:2014-06-19 14:57:36

标签: excel excel-vba import vba

我有一个主Excel工作簿,我想创建一个宏来从7个Excel文件中导入指定范围的数据。除实际数据外,这些文件的结构都相同。使用导入宏/按钮我基本上想要获得一个打开文件对话框,选择所有文件并让宏将范围内的数据逐个添加到主文件中。我从这里的另一篇文章中获得了一些灵感,这使得它适用于单个文件:要调整的代码必须能够选择7个文件并逐个动态地将其添加到目标范围。

 Sub getData()

Dim slaveBook As Workbook
Dim filter As String
Dim caption As String
Dim slaveFilename As String
Dim slaveWorkbook As Workbook
Dim targetWorkbook As Workbook

Set targetWorkbook = Application.ActiveWorkbook

filter = "Team file (*.xlsm),*.xlsm"
caption = "Please select the team file"
slaveFilename = Application.GetOpenFilename(filter, , caption)

Set slaveWorkbook = Application.Workbooks.Open(slaveFilename)

Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets("MASTER")
Dim sourceSheet As Worksheet
Set sourceSheet = slaveWorkbook.Worksheets("Interface")

targetSheet.Range("B5", "J8").Value = sourceSheet.Range("B5", "J8").Value


slaveWorkbook.Close

End Sub

1 个答案:

答案 0 :(得分:0)

Sub getData()

Dim slaveBook As Workbook
Dim filter As String
Dim caption As String
Dim slaveFilename As String
Dim slaveWorkbook As Workbook
Dim targetWorkbook As Workbook

i = 1

For i = 1 To 7

Set targetWorkbook = Application.ActiveWorkbook

On Error GoTo errorhandler

filter = "Team file (*.xlsm),*.xlsm"
caption = "Please select the team file"
slaveFilename = Application.GetOpenFilename(filter, , caption)

Set slaveWorkbook = Application.Workbooks.Open(slaveFilename)
On Error GoTo 0

On Error GoTo err2
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets("MASTER")
Dim sourceSheet As Worksheet
Set sourceSheet = slaveWorkbook.Worksheets("Interface")

If i = 1 Then targetSheet.Range("B5", "J8").Value = sourceSheet.Range("B5", "J8").Value
If i = 2 Then targetSheet.Range("B9", "J12").Value = sourceSheet.Range("B5", "J8").Value
If i = 3 Then targetSheet.Range("B13", "J16").Value = sourceSheet.Range("B5", "J8").Value
If i = 4 Then targetSheet.Range("B17", "J20").Value = sourceSheet.Range("B5", "J8").Value
If i = 5 Then targetSheet.Range("B21", "J24").Value = sourceSheet.Range("B5", "J8").Value
If i = 6 Then targetSheet.Range("B25", "J28").Value = sourceSheet.Range("B5", "J8").Value
If i = 7 Then targetSheet.Range("B29", "J32").Value = sourceSheet.Range("B5", "J8").Value


slaveWorkbook.Close False 'wont prompt to save changes (will close without saving),
                          'remove false if you do need to save changes

i = i + 1

Next i

Exit Sub

errorhandler:

MsgBox "You didn't select a valid file!"
Exit Sub

err2:
MsgBox "Error - Most likely reason is that the required sheet is not found in Slave workbook"
Exit Sub

End Sub

已更新 - 更改了代码,现在它应将所有信息保存到彼此下方的“MASTER”表单中。显然,这是一种非常简单的方法,并且限制您在代码结束之前只打开7个文件。如果您希望将来添加更多内容,您可以简单地扩展数组和范围代码或修改范围代码以查找最后一个可用于粘贴数据的行(LastRow = Range("J65536").End(xlUp).Row)是一个很好的起点