簡體   English   中英

Excel VBA 宏將單元格到列

[英]Excel VBA Macro Taking Cells to Columns

我將數據存儲在單個單元格中:

 <- A (Category) ->   <- B (Items) -> <- C (Items) -> <- D (Items) -> <- E (Items) ->
  1   Cat1                 date1          a,b,c            a1,b1,c1        item1
  2   Cat2                 date2           d                  d1           item2
  3   Cat3                 date3           e,f                e1,f1        item3
  4   Cat4                 date4           g                  g1           item4

我想將其轉換為以下格式:

 <- A (Category) ->   <- B (Items) -> <- C (Items) -> <- D (Items) -> <- E (Items) ->
  1   Cat1                 date1           a                  a1           item1
  1   Cat1                 date1           b                  b1           item1
  1   Cat1                 date1           c                  c1           item1
  2   Cat2                 date2           d                  d1           item2
  3   Cat3                 date3           e                  e1           item3
  3   Cat3                 date3           f                  f1           item3 
  4   Cat4                 date4           g                  g1           item4

(即我想將列 C 和 D 拆分為新行並復制 A、B 和 E 中的項目)。

Excel 宏中的代碼 - 逗號分隔的單元格到行保留/聚合列非常適合兩個相鄰的列,但是如何復制一系列列?

Sub ExpandData()
    Const FirstRow = 2
    Dim LastRow As Long
    LastRow = Range("A" & CStr(Rows.Count)).End(xlUp).Row

    ' Get the values from the worksheet
    Dim SourceRange As Range
    Set SourceRange = Range("A" & CStr(FirstRow) & ":B" & CStr(LastRow))

    ' Get sourcerange values into an array
    Dim Vals() As Variant
    Vals = SourceRange.Value

    ' Loop through the rows in the array and split each comma-delimited list of items and put each on its own row
    Dim ArrIdx As Long
    Dim RowCount As Long
    For ArrIdx = LBound(Vals, 1) To UBound(Vals, 1)

        Dim CurrCat As String
        CurrCat = Vals(ArrIdx, 1)

        Dim CurrList As String
        CurrList = Replace(Vals(ArrIdx, 2), " ", "")

        Dim ListItems() As String
        ListItems = Split(CurrList, ",")

        Dim ListIdx As Integer
        For ListIdx = LBound(ListItems) To UBound(ListItems)

            Range("A" & CStr(FirstRow + RowCount)).Value = CurrCat
            Range("B" & CStr(FirstRow + RowCount)).Value = ListItems(ListIdx)
            RowCount = RowCount + 1

        Next ListIdx

    Next ArrIdx

End Sub

在各個范圍之間使用,

Set SourceRange = Range("A" & CStr(FirstRow) & ":B" & CStr(LastRow) & ",E" & _
                        CStr(FirstRow) & ":E" & CStr(LastRow))

將允許您對 select 脫節范圍。

暫無
暫無

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

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