簡體   English   中英

如何在距離我所在的單元格X列的單元格中寫入(X是在另一個單元格中定義的值)

[英]How can I write in a cell that is X number of column away from the cell I am on (X is a value defined in another cell)

我有一組物品被歸類為A/B/C 例如:

項目和類別:

在此輸入圖像描述

我想將A / B / C作為列,但是將每個項目放在一起。 例如:

每個項目作為列:

在此輸入圖像描述

如果每個類別下可以有任意數量的項目,我該怎么辦?

我認為宏可以實現這一點,但我希望盡可能避免從宏中清除。

修改代碼並嘗試:

Option Explicit

Sub TEST()

    Dim LastRow As Long, LastColumn As Long, LastColumn2 As Long, i As Long, y As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")

        arr = Array("A", "B", "C") '<- Create an array with the desirable Items

        For i = LBound(arr) To UBound(arr) '<- Loop array
            'Find Last column of row 12 in order to import Titles
            LastColumn = .Cells(12, .Columns.Count).End(xlToLeft).Column

            If LastColumn = 1 And .Cells(11, LastColumn).Value = "" Then
                .Cells(11, LastColumn).Value = arr(i)
            Else
                .Cells(11, LastColumn + 1).Value = arr(i)
            End If
            'Find Last row of column B in order to create the loop range
            LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
            'Loop column B from 1 to last row of column B
            For y = 1 To LastRow
                'Check if looping value is the same with array value
                If .Range("B" & y).Value = arr(i) Then
                    'Find Last column of row 12 in order to import values
                    LastColumn2 = .Cells(12, .Columns.Count).End(xlToLeft).Column

                    If LastColumn2 = 1 And .Cells(12, LastColumn2).Value = "" Then
                        .Cells(12, 1).Value = .Range("A" & y).Value
                    Else
                        .Cells(12, LastColumn2 + 1).Value = .Range("A" & y).Value
                    End If

                End If

            Next y

        Next i

    End With

End Sub

結果:

在此輸入圖像描述

暫無
暫無

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

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