我想从3个名为Sub WB1,Sub WB2和Sub WB3的不同工作簿中将名为“任务跟踪”的工作表内容合并到单个主工作簿任务跟踪工作表中。请帮忙。将来自不同工作簿的数据合并到主工作簿的特定工作表
共有4个工作簿,每个工作簿共12个工作表。
- 主簿
- 子WB1
- 子WB2
- 子WB3
我想从小组WB1合并来自 “任务跟踪”(工作表名)的数据,分WB2并使用主工作簿中的Consolidate按钮将Sub WB3转换为主工作簿。
我用下面的代码,我从一些参考,但我得到运行时错误:1004请帮助。作为 "Sub WB1.xlsm, Sub WB2.xlsm, Sub WB3.xlsm"
,如果你想给用户给定的名称来选择文件,只有这样,你必须使用一个用户窗体
例如
Sub MergeSpecificWorkbooks()
Dim MyPath As String
Dim SourceRcount As Long, FNum As Long
Dim mybook As Workbook, BaseWks As Worksheet
Dim sourceRange As Range, destrange As Range
Dim rnum As Long, CalcMode As Long
Dim SaveDriveDir As String
Dim FName As Variant
'Change ScreenUpdating, Calculation and EnableEvents
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
'SaveDriveDir = CurDir
'ChDirNet "D:\DD_Task1\"
path = "D:\DD_Task1\"
'FName = Application.GetOpenFilename("Sub WB1.xls, Sub WB2.xls, Sub WB3.xls", MultiSelect:=True)
FName = Application.GetOpenFilename(filefilter:="Sub WB1.xlsm, Sub WB2.xlsm, Sub WB3.xlsm", _
MultiSelect:=True)
If IsArray(FName) Then
'Add a new workbook with one sheet
'Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
Set BaseWks = Worksheets.Add
BaseWks.Name = "Master"
rnum = 2
'Loop through all files in the array(myFiles)
For FNum = LBound(FName) To UBound(FName)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(FName(FNum))
On Error GoTo 0
If Not mybook Is Nothing Then
On Error Resume Next
With mybook.Worksheets("H-POD")
.Unprotect
LC = .Cells(.Rows.Count, "C").End(xlUp).Row
Set sourceRange = .Range("B10:M" & LC)
End With
If Err.Number > 0 Then
Err.Clear
Set sourceRange = Nothing
Else
'if SourceRange use all columns then skip this file
If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
Set sourceRange = Nothing
End If
End If
On Error GoTo 0
If Not sourceRange Is Nothing Then
SourceRcount = sourceRange.Rows.Count
If rnum + SourceRcount >= BaseWks.Rows.Count Then
MsgBox "Sorry there are not enough rows in the sheet"
BaseWks.Columns.AutoFit
mybook.Close savechanges:=False
GoTo ExitTheSub
Else
'Copy the file name in column A
With sourceRange
BaseWks.Cells(rnum, "A"). _
Resize(.Rows.Count).Value = FName(FNum)
End With
'Set the destrange
Set destrange = BaseWks.Range("B" & rnum)
'we copy the values from the sourceRange to the destrange
With sourceRange
Set destrange = destrange. _
Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = sourceRange.Value
rnum = rnum + SourceRcount
End If
End If
mybook.Close savechanges:=False
End If
Next FNum
BaseWks.Columns.AutoFit
End If
ExitTheSub:
'Restore ScreenUpdating, Calculation and EnableEvents
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
' ChDirNet SaveDriveDir
End Sub
感谢您的帮助!此代码显示列表框但不合并数据。 :( – Maaya
你的帮助请求是关于_“运行时错误:1004”_,并且这个解决方案解决了这个问题,然后你可能想把这个答案标记为可接受的,而如果你遇到了合并代码的问题,最小的“环境” – user3598756
@Maaya;有什么问题:我的解决方案不会回答你的_original_问题吗? – user3598756