我使用此脚本插入填充行,其中在 Excel 文件的列中生成非连续行。
Sub InsertValueBetween()
Dim lastrow As Long
Dim gap As Long
Dim i As Long, ii As Long
Application.ScreenUpdating = False
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = lastrow To 3 Step -1
gap = .Cells(i, "A").Value - .Cells(i - 1, "A").Value
If gap > 1 Then
.Rows(i).Resize(gap - 1).Insert
End If
Next i
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Cells(3, "A").Value = .Cells(2, "A").Value + 1
.Cells(2, "A").Resize(2).AutoFill .Cells(2, "A").Resize(lastrow - 1)
End With
End Sub
除了添加这些新行之外,我希望它们在 B 列中也有一个特定值。我正在尝试实现这一点,但没有结果。
有人可以帮助我吗?
最佳答案
解决这一挑战的一种方法是使用 Range
变量。以下是一些经过大量注释的代码,用于演示整个过程:
Sub InsertValueBetweenRev2()
Dim Target As Range '<~ declare the range variable
'... declare your other variables
'... do other stuff
For i = lastrow To 3 Step -1
gap = .Cells(i, "A").Value - .Cells(i - 1, "A").Value
If gap > 1 Then
.Rows(i).Resize(gap - 1).Insert
'the next line sets the range variable to the recently
'added cells in column B
Set Target = .Range(.Cells(i, 2), .Cells(i + gap - 2, 2))
Target.Value = "Cool" '<~ this line writes text "Cool" into those cells
End If
Next i
'... the rest of your code
End Sub
总而言之,我们知道将添加 gap - 1
行,并且我们知道新行是从第 i
行开始添加的。利用这些知识,我们将 B 列中刚刚添加的单元格分配给 Range
,然后将该 Range
的 .value
设置为所需的值.
关于vba - 在 Excel 中插入具有特定单元格中的值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24181242/