将简单的excel宏实现为复杂的宏

时间:2013-02-27 18:37:31

标签: vba excel-vba excel

这个宏可以正常工作,因为它不应该对文件进行条件过滤。

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

上下文

我在位于文件路径.txt的文件夹中有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")

当我尝试为我的需要采用这个宏时,我的意思是把它放在“复杂”宏中的这个排序部分之后并删除以前复制文件的方式,我就是无法使它工作。

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

P.S。我的文件结构是3列,每行约有18000行。

1 个答案:

答案 0 :(得分: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