我正在尝试创建一个Excel宏,该宏将采用其中包含n
行数的电子表格,并将每行复制为位于其中一个单元格内的数字的次数。
它还会增加一个单元格中的一个数字。例如,我有如下布局:
Column1 Column2 Column3 Column4, etc..
Data-a Data-a 1000 5
Data-b Data-b 4600 10
结果将是:
Column1 Column2 Column3 Column4
Data-a Data-a 1000 5
Data-a Data-a 1001 5
Data-a Data-a 1002 5
Data-a Data-a 1003 5
Data-a Data-a 1004 5
Data-b Data-b 4600 10
Data-b Data-b 4601 10
Data-b Data-b 4602 10
Data-b Data-b 4603 10
Data-b Data-b 4604 10
Data-b Data-b 4605 10
Data-b Data-b 4606 10
Data-b Data-b 4607 10
Data-b Data-b 4608 10
Data-b Data-b 4609 10
希望这是有道理的。我正在寻找一个可能对这种类型的宏更精通的人来揭示一些亮点或指出我正确的方向。
答案 0 :(得分:1)
我测试了这段代码,似乎工作正常。要完成这项工作,您需要在初始数据列表中选择“数据-a”,即左上角的单元格。
有三个程序:
Sub InsertNewRows(TargetRow As Integer, TargetCol As Integer, Reps As Integer)
Dim iRep As Integer
For iRep = 1 To Reps - 1
Cells(TargetRow + iRep, TargetCol).EntireRow.Insert Shift:=xlDown
Next iRep
End Sub
Sub ReplicateData(TargetRow As Integer, TargetCol As Integer, Reps As Integer)
Dim iRep As Integer
For iRep = 1 To Reps - 1
With Cells(TargetRow, TargetCol)
.Offset(iRep, 0).Value = .Value
.Offset(iRep, 1).Value = .Offset(0, 1).Value
.Offset(iRep, 2).Value = .Offset(0, 2).Value + iRep
.Offset(iRep, 3).Value = .Offset(0, 3).Value
End With
Next iRep
End Sub
Sub TransformData()
Dim nRows As Long
nRows = ActiveCell.CurrentRegion.Rows.Count
Dim StartingRow As Integer
Dim StartingColumn As Integer
Dim NumberOfReplications As Integer
Dim RowOffset
StartingRow = ActiveCell.Row
StartingColumn = ActiveCell.Column
NumberOfReplications = 0
RowOffset = 0
Dim iIterations As Integer
For iIterations = 1 To nRows
If Not VBA.IsEmpty(Cells(StartingRow + RowOffset, StartingColumn)) Then
NumberOfReplications = Cells(StartingRow + RowOffset, StartingColumn).Offset(0, 3)
InsertNewRows StartingRow + RowOffset, StartingColumn, NumberOfReplications
ReplicateData StartingRow + RowOffset, StartingColumn, NumberOfReplications
RowOffset = RowOffset + NumberOfReplications
End If
Next iIterations
End Sub