0

此宏按其应有的方式工作,无需对文件进行条件过滤。

但是我只需要修改这个宏,以便它打开每个文件,从最小到最大对它们进行排序,只过滤那些高于平均水平的文件,现在从这些文件中获取前 100 个并将它们复制到新的工作表中,首先这 100 行中的一行粗体。

语境

.txt在位于 filepath 的文件夹中有 600 个 excel 文件(实际上扩展名为 )C:\Excel。此宏打开它们中的每一个,从最小值到最大值对它们进行排序,从每个中取出前 100 个,并在打开文件时按顺序将它们复制到新工作表中,使新文件的第一行变为粗体。

这是代码:

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

    Dim isEmpty As String
    isEmpty = "null"

    ' Change this to the path\folder location of your files.
    MyPath = "C:\Excel"

    ' 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 & "*.txt")
    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

    ' Add a new workbook with one sheet.
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    rnum = 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

                    mybook.Worksheets(1).Sort.SortFields.Clear
                    mybook.Worksheets(1).Sort.SortFields. _
                    Add Key:=Range("C2:C18000"), SortOn:=xlSortOnValues, Order:=xlAscending, _
                    DataOption:=xlSortNormal

                 ' Change this range to fit your own needs.
                With mybook.Worksheets(1)
                    Set sourceRange = .Range("A2:C101")
                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, "D").Font.Bold = True
                           ' BaseWks.Cells(rnum, "D"). _
                                    Resize(.Rows.Count).Value = MyFiles(FNum)
                       ' End With

                        ' Set the destination range.

                        Set destrange = BaseWks.Range("A" & rnum)



                        With mybook.Worksheets(1).Sort
                                .SetRange Range("A1:C18000")
                                .Header = xlYes
                                .MatchCase = False
                                .Orientation = xlTopToBottom
                                .SortMethod = xlPinYin
                                .Apply
                            End With

                        ' Copy the values from the source range
                        ' to the destination range.
                        With sourceRange
                            BaseWks.Cells(rnum, "A").Font.Bold = True
                            BaseWks.Cells(rnum, "B").Font.Bold = True
                            BaseWks.Cells(rnum, "C").Font.Bold = True
                            'MsgBox (BaseWks.Cells.Address)
                            If ActiveCell.Text = isEmpty Then
                            ActiveCell.Offset(0, 1) = 1
                            ActiveCell.Offset(1).EntireRow.Insert
                            ActiveCell.Offset(1, 1) = 0
                            End If
                            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

宏是凌乱的,但它的工作。

研究

我设法找到了一些宏并采用了它们,所以这是活动工作表中的宏,它只过滤那些高于平均水平的数据,并取前 100 个并将它们复制到同一工作簿的 sheet2 中。

Range("A1").Select
    Selection.AutoFilter
    ActiveSheet.Range("A1:C18000").AutoFilter Field:=3, Criteria1:= _
        xlFilterAboveAverage, Operator:=xlFilterDynamic
   ActiveSheet.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Rows("1:100").Copy Destination:=Sheets("Sheet2").Range("A1")

当我尝试根据需要采用此宏时,我的意思是将其放在“复杂”宏中的此类部分之后并删除以前复制文件的方式,但我无法使其正常工作。

我也问了这个问题并得到了一个可能的解决方案来获取前 100 行过滤数据(我在“简单宏”中找到这个方法之前问过这个),但是我仍然不知道如何完成过滤。所以我问这个问题,因为我需要这个尽快。

PS 我的文件结构是 3 列,每列大约有 18000 行。

4

1 回答 1

1

我尝试遵循您现有的代码,但老实说有点混乱(您已经承认)。我重写了我相信你正在尝试做的事情。这确实依赖于 Scripting Runtime 组件,因此在 VBA 窗口中,转到 Tools...References... 并单击 Microsoft Scripting Runtime。

由于您已经对数据进行了排序,因此不需要过滤器。此外,您没有指定要排序的列,您的代码将按 A 排序,所以我假设。

我没有考虑任何特殊情况......即有超过 18000 行,有不到 100 个高于平均值的值,等等。您可能可以调整您以前的一些代码来处理这种情况。

Sub StackExample()

Dim fso As New Scripting.FileSystemObject
Dim fo As Scripting.Folder
Dim f As Scripting.File

Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim wsPaste As Excel.Worksheet

Dim avg As Double
Dim r As Long

    Set fo = fso.GetFolder("C:\Excel\")

    For Each f In fo.Files
        If Right(f.Name, 4) = ".txt" Then

            ' assign the variable objects
            Set wb = Excel.Workbooks.Open(fo.Name & f.Name)
            Set ws = wb.Worksheets(1)
            wb.Worksheets.Add
            Set wsPaste = wb.Worksheets(1)
            wsPaste.Move , ws

            ' text to columns (from TXT file)
            ws.Activate
            ws.Range("A1:A18000").TextToColumns DataType:=xlDelimited, Comma:=True

            ' sort
            With ws.Sort
                .SetRange Range("A1:C18000")
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlSortColumns
                .SortMethod = xlPinYin
                .Apply
            End With

            ' calculate the average
            avg = Excel.WorksheetFunction.Average(ws.Range("A2:A18000"))

            ' find the first row with a value equal to or greater than the average
            For r = 2 To 18000
                If ws.Cells(r, 1).Value >= avg Then Exit For
            Next r

            ' copy the range, then paste
            ws.Range(ws.Cells(r, 1), ws.Cells(r + 99, 3)).Copy
            wsPaste.Activate
            wsPaste.Paste wsPaste.Range("A1")

            ' save and close
            Application.DisplayAlerts = False
            wb.SaveAs Left(f.Name, Len(f.Name) - 4), xlOpenXMLWorkbook
            wb.Close
            Application.DisplayAlerts = True

        End If
    Next f

End Sub
于 2013-02-28T01:14:07.657 回答