VBA中的多个范围选择 - 将多个工作簿合并到一个主工作簿中

时间:2016-05-10 17:06:03

标签: excel-vba vba excel

我正在尝试将同一文件夹中的一些工作簿合并到主工作簿中以进行制图。我使用Ron De Bruin's code来完成此任务。到目前为止,一切都很顺利。我只需要一个功能,使其适合我的应用程序。

在代码中,所选择的源范围在一个完整的大范围内(B12:H316),并且我必须使用数据透视表来过滤它。实际上,我只需要B12:H12,B20:H20,B316:H316。我尝试了许多调整,例如Set SourceRange = Union(.Range("B12:H12"), .Range("B20:H20"), .Range("B316:H316"))以及Set SourceRange = .Range("B12:H12","B20:H20","B316:H316")但到目前为止没有任何效果。

我有没有想要调整代码行,以便我只能选择B12:H12,B20:H20和B316:H316作为从每个工作簿中复制的源范围。特定文件夹?

据我所知,Ron De Bruin有一个附加功能,可以满足多种范围的需求。但是,由于某些公司政策,我无法使用它。

以下是我现在的代码:

Sub MergeAllWorkbooks()
Dim MyPath As String, FilesInPath As String
Dim MyFiles() 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

' Change this to the path\folder location of your files.
MyPath = "C:\Users\Captain\Desktop\Target Test"

' Add a slash at the end of the path if needed.
If Right(MyPath, 1) <> "\" Then
    MyPath = MyPath & "\"
End If

' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xl*")
If FilesInPath = "" Then
    MsgBox "No files found"
    Exit Sub
End If

' Fill the myFiles array with the list of Excel files
' in the search folder.
FNum = 0
Do While FilesInPath <> ""
    FNum = FNum + 1
    ReDim Preserve MyFiles(1 To FNum)
    MyFiles(FNum) = FilesInPath
    FilesInPath = Dir()
Loop

' Set various application properties.
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
End With

' Use existing sheet
Set BaseWks = Workbooks("SPC.xlsm").Worksheets("RawData")
rnum = BaseWks.Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1


' Loop through all files in the myFiles array.
If FNum > 0 Then
    For FNum = LBound(MyFiles) To UBound(MyFiles)
        Set mybook = Nothing
        On Error Resume Next
        Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
        On Error GoTo 0

        If Not mybook Is Nothing Then
            On Error Resume Next

            ' Change this range to fit your own needs.

            With mybook.Worksheets(1)

            Set SourceRange = .Range("B12:H316")

                End With

            If Err.Number > 0 Then
                Err.Clear
                Set SourceRange = Nothing
            Else
                ' If source range uses 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 "There are not enough rows in the target worksheet."
                    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 = MyFiles(FNum)
                    End With

                    ' Set the destination range.
                    Set DestRange = BaseWks.Range("B" & rnum)

                    ' Copy the values from the source range
                    ' to the destination range.
                    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 the application properties.
With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = CalcMode
End With
End Sub

我感谢任何形式的帮助。非常感谢您的时间。

1 个答案:

答案 0 :(得分:0)

使用Set SourceRange = Union(.Range("B12:H12"), .Range("B20:H20"), .Range("B316:H316"))会有效,但会产生一些奇怪的副作用。如果联盟创造了一个&#34;连续的&#34;范围(例如&#34; B12:H15&#34;),然后一切正常。因为它有行间隙,所以你不能得到通常预期的结果。

SourceRange.Rows.Count的计算结果为1,因此SourceRCount的值不正确。

1)替换此片段......

SourceRcount = SourceRange.Rows.Count

......有了......

Dim aRow as Range
SourceRCount = 0
For Each aRow In SourceRange.Rows
    SourceRCount = SourceRCount + 1
Next aRow

2)此外,以下代码片段需要更正......

    With SourceRange
        BaseWks.Cells(rnum, "A"). _ 
            Resize(.Rows.Count).Value = MyFiles(FNum)
    End With

...可能对此...

    BaseWks.Cells(rnum, "A").Resize(SourceRCount).Value = MyFiles(FNum)

3)此片段......

    With SourceRange
        Set DestRange = DestRange. _
                        Resize(.Rows.Count, .Columns.Count)
    End With

...应该成为(Columns.Count正常工作)......

    Set DestRange = DestRange.Resize(SourceRCount, SourceRange.Columns.Count)

4)最后,这项任务将无法按预期工作......

    DestRange.Value = SourceRange.Value

......应该改为......

Dim RCount as long
RCount = 0
For Each aRow In SourceRange.Rows
    RCount = RCount + 1
    DestRange.Rows(RCount).Value = aRow.Value
Next aRow