如何修改VBA代码实现按F列值插入行并复制对应H列值到新行
修改后的VBA代码
Sub Add_Rows() Dim r As Long Dim insertCnt As Long Application.ScreenUpdating = False For r = Range("F" & Rows.Count).End(xlUp).Row To 1 Step -1 insertCnt = Cells(r, "F").Value If insertCnt > 0 Then Rows(r + 1).Resize(insertCnt).Insert Range(Cells(r + 1, "H"), Cells(r + insertCnt, "H")).Value = Cells(r, "H").Value End If Next r Application.ScreenUpdating = True End Sub
改动说明
- 新增
insertCnt变量存储当前行F列的插入行数,避免重复读取单元格内容,同时防止插入行后取值出现偏差 - 插入行操作完成后,直接批量对新插入行的H列赋值为原行H列的内容,无需循环单个单元格赋值,执行效率更高
内容的提问来源于stack exchange,提问作者Foertsch
相关产品推荐
相关产品推荐

