我想写一个Excel VBA的重复项目的几列

iyr7buue  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(111)

我想知道如何写的excel VBA为这个重复的项目,如照片所示?左边是我的数据,右边是我想实现的目标答案。我试图找到代码,但它是徒劳的,有人能请帮助吗?谢谢。

Sub repeat_items()

'----variables
Dim lrow_d As Long
Dim lrow_s As Long

'-----Sheets
Dim s_sht As Worksheet

'-----Define Sheet names
Set s_sht = Worksheets("Repeat")

'--LastRow
lrow_s = s_sht.Cells(Rows.Count, 1).End(xlUp).Row

'---Creating repeating
s_sht.Range("D2:D1000000").Clear

For i = 2 To lrow_s         'count no. 2 of column A from up to down

lrow_d = s_sht.Cells(Rows.Count, 4).End(xlUp).Row

s_sht.Range("A" & i).copy Destination:=s_sht.Range("D" & lrow_d + 1 & ":" & "D" & lrow_d + s_sht.Range("B" & i))
            '+1 is bottom next row      'D is the column D location         'B is calculating number of times from column B

Next i

End Sub
btxsgosb

btxsgosb1#

根据您提供的屏幕截图,类似的操作应该适合您。请确保根据需要更新工作表名称,如果您希望目标位于其他位置,请调整目标。(如果您希望目标位于其他工作表,则需要添加新的工作表变量)。

Sub repeat_items()
    
    'Declare and set variables
    Dim ws As Worksheet:    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Dim rData As Range:     Set rData = ws.Range("A1").CurrentRegion
    Dim rDest As Range:     Set rDest = ws.Range("H2")
    If rData.Rows.Count = 1 Then Exit Sub  'No data
    Dim aData As Variant:   aData = rData.Value
    
    'Prepare results array
    Dim aResults() As Variant, iResult As Long
    ReDim aResults(1 To WorksheetFunction.Sum(rData), 1 To 1)
    
    'Prepare loop variables
    Dim i As Long, j As Long, k As Long, sResult As String
    
    'Loop through each row
    For i = 2 To UBound(aData, 1)
        sResult = vbNullString      'Reset the result string to null
        
        'Loop through each column
        For j = 1 To UBound(aData, 2)
            
            'Check if the value in the data is a number or not
            If Not IsNumeric(aData(i, j)) Then
                'Not a number, add the text to the result string with an "_"
                sResult = sResult & aData(i, j) & "_"
            Else
                'This is a number, loop that number of times
                For k = 1 To aData(i, j)
                    'Each time, add this column header to the result string and append it to the results array
                    iResult = iResult + 1
                    aResults(iResult, 1) = sResult & aData(1, j)
                Next k
            End If
        Next j
    Next i
    
    rDest.Resize(rDest.CurrentRegion.Rows.Count).ClearContents
    rDest.Resize(UBound(aResults, 1)).Value = aResults  'Output results
    
End Sub

相关问题