2016-09-27 149 views
-1

所以我有一個大型數據集,我想合併行取決於如果第一列中的信息匹配到一定程度。我想知道是否有宏可以做到這一點。下面我列出了一個類似簡化數據集的圖像。我會假設宏將在新工作表中創建新表或在現有數據下插入一行,但我不確定。任何有關此問題的幫助或提示都會非常有幫助。Excel VBA插入行,如果單元格匹配第一個字符

樣本數據集:

Sample Dataset

輸出:

Output

+0

請發佈提問之前做一些研究。特別是關於如何提出好問題,還要檢查類似的問題。當條件滿足時,這裏有數百個宏插入行。 – teylyn

+0

嗯,謝謝我猜 –

回答

0

,你可以嘗試以下的(註釋)代碼:

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 
+0

無論發生「本網站不是免費代碼寫作服務」還是「發佈您遇到問題的代碼」?你邀請人們不要做任何工作,因爲你正在爲他們做。 – teylyn

+0

它的工作!非常感謝你user3598756!我沒有發佈代碼,因爲我甚至不知道從哪裏開始,需要幫助/指導。我從不指望有人寫一個完整的代碼。相反,我期待有人提供提示/幫助編寫代碼,但我非常感謝您的幫助! –

+0

不客氣。然後,您可能想要將答案標記爲已接受。 – user3598756

0

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

+0

不是幾個字符,但他可以使用文本分隔行「」。 –

相關問題