我有一份需要重新组织的记录列表。它们的格式如下。 ID是与以下5行对应的数字。我需要在每个行旁边的A列中存在这个数字及其相应的ID号。 我需要ID列存在于A列中,如第二张图片中所示。这需要在宏中使用VBA来完成,因为有超过100条记录。
有人能指出我正确的方向吗?我不确定引用ID字段的最佳方式,而不像下面的代码那样逐一进行...
Range("A2").Select
Selection.AutoFill Destination:=Range("A2:A5"), Type:=xlFillDefault
Range("A2:A5").Select
Range("A7").Select
ActiveCell.FormulaR1C1 = "=R6C[2]"
Range("A7").Select
Selection.AutoFill Destination:=Range("A7:A10"), Type:=xlFillDefault
Range("A7:A10").Select
Range("A12").Select
ActiveCell.FormulaR1C1 = "=R11C[2]"
答案 0 :(得分:1)
假设: 从第1行开始,您的数据组将出现在“B”列中,并在名为“Sheet1”的工作表中包含4个附加记录
Public Sub AutoFillRecordGroup()
Dim irecordgroup as Integer
Dim xlrange as Excel.Range
Dim varcell as Variant
Set xlrange = ThisWorkbook.Sheets("Sheet1").Range("B1" & ThisWorkbook.Sheets("Sheet1").Range("B1048576").End(xlup).Address)
irecordgroup = 1
For Each varcell in xlrange
If varcell.value = "ID" Then
varcell(1,-1).value = irecordgroup
varcell(2,-1).value = irecordgroup
varcell(3,-1).value = irecordgroup
varcell(4,-1).value = irecordgroup
irecordgroup = irecordgroup + 1
End If
Next varcell
End Sub
或
Public Sub AutoFillRecordGroup()
Dim irecordgroup as Integer
Dim xlrange as Excel.Range
Dim varcell as Variant
Set xlrange = ThisWorkbook.Sheets("Sheet1").Range("B1" & ThisWorkbook.Sheets("Sheet1").Range("B1048576").End(xlup).Address)
irecordgroup = 1
For Each varcell in xlrange
If varcell.value = "ID" Then
varcell(1,-1).value = varcell(0,1).value
varcell(2,-1).value = varcell(0,1).value
varcell(3,-1).value = varcell(0,1).value
varcell(4,-1).value = varcell(0,1).value
irecordgroup = irecordgroup + 1
End If
Next varcell
End Sub