2017-08-23 97 views
0

我在Excel中兩列組:Excel宏幫助 - 通過

TableName Function 
    100  abc 
    100  def 
    100  xyz 
    100  ghy 
    100  ajh 
    101  ahd 
    101  lkj 
    101  gtr 
    102  afg 
    102  vbg 
    102  arw 
    102  fgtr 

我需要爲

TableName  Function 
    100  abc,def,xyz,ghy,ajh, 
    101  ahd,lkj,gtr, 
    102  102,102,102,102, 
+0

樞+宏錄製會做一個完美的工作。 – Vityata

回答

0

如果輸出符合你的VBA的解決方案,然後以下可能的幫助。

Sub Demo() 
    Dim ws As Worksheet 
    Dim rng As Range 
    Dim lastRow As Long 
    Dim dic As Variant, arr As Variant, temp As Variant 

    Application.ScreenUpdating = False 
    Set ws = ThisWorkbook.Sheets("Sheet4") 'change Sheet4 to your data sheet 

    With ws 
     lastRow = Cells(Rows.count, "A").End(xlUp).row 'get last row with data in Column A 
     Set rng = .Range("A2:B" & lastRow)    'set the range of data 
     Set dic = CreateObject("Scripting.Dictionary") 
     arr = rng.Value 
     For i = 1 To UBound(arr, 1) 
      temp = arr(i, 1) 
      If dic.Exists(temp) Then 
       dic(arr(i, 1)) = dic(arr(i, 1)) & ", " & arr(i, 2) 
      Else 
       dic(arr(i, 1)) = arr(i, 2) 
      End If 
     Next 
     .Range("D1") = "Table Name"   'display headers 
     .Range("E1") = "Function" 
     .Range("D2").Resize(dic.count, 1) = Application.WorksheetFunction.Transpose(dic.keys) 'display table names 
     .Range("E2").Resize(dic.count, 1) = Application.WorksheetFunction.Transpose(dic.items) 'display funtions 
    End With 
    Application.ScreenUpdating = True 
End Sub 

結果將如下圖所示。

enter image description here

從Excel中添加此代碼按Alt鍵+ F11 。這將打開Microsoft Visual Basic編輯器,然後單擊Insert>Module並粘貼上面的代碼。按F5執行該代碼。

+0

非常感謝..它的工作非常好。 :) – Atul

+0

嗨Mrig,對於列B我有這樣的值如下所示。它不適用於此。它說運行時錯誤13.看起來像一些數據類型錯誤。樣本列B的值是cast(nvl(concat(To_date(from_unixtime(unix_timestamp(sostmp,'ddMMMyyyy'))),'',substr(sostmp,11,20)),'0001-01-01 00:00:00.000000 ')作爲時間戳), – Atul

0

你可以試試這個簡單的代碼,

Sub joinStr() 
Dim i As Long, str As String, k As Long 
Columns("A:B").Sort key1:=Range("A2"), order1:=xlAscending, Header:=xlYes 
str = Cells(2, 2) 
k = 2 
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row 
    If Cells(i, 1) = Cells(i + 1, 1) Then 
     str = str & "," & Cells(i + 1, 2) 
    Else 
     Cells(k, 4) = Cells(i, 1) 
     Cells(k, 5) = str 
     k = k + 1 
     str = Cells(i + 1, 2) 
    End If 
Next i 
End Sub 

enter image description here

+0

感謝它的工作完美的罰款/數據的預期。 – Atul

+0

@Atul很棒。請將答案標記爲正確以使其得到解決 –