簡體   English   中英

Excel VBA 如果單元格匹配第一個字符,則插入行

[英]Excel VBA Insert row if cells match first characters

所以我有一個大數據集,我想根據第一列中的信息是否在一定程度上匹配來組合行。 我想知道是否有一個宏可以做到這一點。 下面我包含了一個類似的簡化數據集的圖像。 我假設宏會在新工作表中創建新表或在現有數據下方插入一行,但我不確定。 關於這個問題的任何幫助或提示都會非常有幫助。

示例數據集:

樣本數據集

輸出:

輸出

添加一列,提取第一列的前幾個字符。 然后創建一個數據透視表,其中包含行中的新列和值區域中的其他列。 不需要VBA。

您可以嘗試以下(注釋)代碼:

Option Explicit

Sub main()
    Dim cell As Range, cell2 As Range

    With Worksheets("experiment").Range("A1").CurrentRegion '<--| reference data worksheet(change "experiment" to its actual name) cell "A1" contiguous range column "A"
        .Sort key1:=Range("A1"), order1:=xlAscending, Header:=xlYes '<--| sort it by "experiment" column to have "smaller" names at the top
        For Each cell In .Offset(1).Resize(.Rows.Count - 1, 1) '<--| loop through its 1st column cells skipping header row
            If cell.Value <> "" Then '<--| if current cell isn't blank (also as a result of subsequent operations)
                .AutoFilter Field:=1, Criteria1:="*" & cell.Value & "*" '<--| filter on referenced column to get cell "containing" current cell content
                If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 2 Then '<--| if more than 2 rows has been foun: header row gets always filtered so to have at least 2 rows to consolidate we must filter at least 3
                    With .Offset(1).Resize(.Rows.Count - 1) '<--| reference filtered rows skipping header row
                        For Each cell2 In .Offset(, 1).Resize(, .Columns.Count - 1).SpecialCells(xlCellTypeVisible).Areas(1).Rows(1).Cells '<--| loop through 1st filtered row cells skipping 1st column ("experiment")
                            cell2.Value = WorksheetFunction.Subtotal(9, cell2.EntireColumn) '<--| update their content to the sum of filtered cells in corresponding column
                        Next cell2
                        With .Resize(, 1).SpecialCells(xlCellTypeVisible) '<--| reference filtered rows 1st column ("experiment") cells
                            .Value = .Cells(1, 1) '<--| have them share the same name
                        End With
                        .RemoveDuplicates Columns:=Array(1), Header:=xlNo '<--| remove duplicates, thus leaving the 1st filtered row with totals
                    End With
                End If
            End If
        Next cell
        .Parent.AutoFilterMode = False '<--| show all rows back
    End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM