Copying multiple cells in same row based on multiple criteria

后端 未结 1 788
礼貌的吻别
礼貌的吻别 2021-01-28 04:01

Background: I have an Excel file used for tracking credit card payables. There are 18 columns of data (A through R). Out of these 18 columns, I want to use a macro to filter for

相关标签:
1条回答
  • 2021-01-28 04:54

    Here's a sub that should get you started. I did not implement all your steps, but I believe this is enough to take and finish on your own. If you find this answer is helpful to get you where you need to go, please accept this answer. If you have problems with anything here, please add a comment to this answer asking for clarification.

    I have only tested on dummy data, but what I did work with was successful.

    Option Explicit
    
    Sub TransferData()
    Dim Master As Worksheet
    Dim NewSheet As Worksheet
    Dim CompanyList As Object
    Dim lRow As Long, lMaxRow As Long, lNewRow As Long
    Dim vDictItem As Variant
    
    Set CompanyList = CreateObject("Scripting.Dictionary")
    
    Set Master = ThisWorkbook.Sheets("Master")
    
    If Master.FilterMode Then
        Master.ShowAllData
    End If
    
    Master.Range("A:R").Sort Master.Range("A2"), xlAscending, Master.Range("O2"), , xlAscending, , , xlYes
    
    lMaxRow = Master.Range("A" & Master.Rows.Count).End(xlUp).Row
    For lRow = 3 To lMaxRow
        If Not CompanyList.Exists(Master.Range("A" & lRow).Value) Then
            CompanyList.Add Master.Range("A" & lRow).Value, Master.Range("A" & lRow).Value
        End If
    Next lRow
    
    For Each vDictItem In CompanyList.Keys
        Master.Range("A3:R" & lMaxRow).AutoFilter 1, vDictItem
        If Master.Cells.SpecialCells(xlCellTypeVisible).Count > 0 Then
            Set NewSheet = ThisWorkbook.Worksheets.Add
            NewSheet.Name = vDictItem
            lNewRow = 1
            For lRow = 3 To lMaxRow
                If Master.Rows(lRow).Hidden = False Then
                    lNewRow = lNewRow + 1
                    NewSheet.Range("C1").Value = Master.Range("P1").Value
                    NewSheet.Range("C" & lNewRow).Value = Master.Range("P" & lRow).Value
                    NewSheet.Range("G1").Value = Master.Range("F1").Value
                    NewSheet.Range("G" & lNewRow).Value = Left(Master.Range("F" & lRow).Value, 30)
                    NewSheet.Range("E1").Value = Master.Range("G1").Value & " (POS)"
                    NewSheet.Range("F1").Value = Master.Range("G1").Value & " (NEG)"
                    If Master.Range("G" & lRow).Value >= 0 Then
                        NewSheet.Range("E" & lNewRow).Value = Left(Master.Range("G" & lRow).Value, 30)
                    Else
                        NewSheet.Range("F" & lNewRow).Value = Left(Master.Range("G" & lRow).Value, 30)
                    End If
                End If
            Next lRow
        End If
    Next vDictItem
    
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题