【问题标题】:Multiple range selection in VBA - Consolidating multiple workbooks into one master workbookVBA 中的多范围选择 - 将多个工作簿合并到一个主工作簿中
【发布时间】:2016-05-10 17:06:02
【问题描述】:

我正在尝试将同一个文件夹中的几个工作簿合并到一个主工作簿中以用于图表目的。我正在使用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

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

【问题讨论】:

  • 惊讶 union 没用。你总是可以做三遍 XD

标签: excel vba


【解决方案1】:

使用Set SourceRange = Union(.Range("B12:H12"), .Range("B20:H20"), .Range("B316:H316")) 会起作用,但会产生一些奇怪的副作用。如果联盟创建了一个“连续”范围(例如“B12:H15”),那么一切都会正常。因为它有 Row gaps,所以你不会得到正常预期的结果。

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

1) 替换这个sn-p ...

SourceRcount = SourceRange.Rows.Count

...用这个...

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

2) 另外,下面的 sn-p 需要更正...

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

...大概到这个...

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

3) 这个sn-p ...

    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

【讨论】:

  • 感谢您的宝贵意见
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
相关资源
最近更新 更多