vba - 在 Excel 中插入具有特定单元格中的值的行

标签 vba excel

我使用此脚本插入填充行,其中在 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/

相关文章:

ms-access - 确定函数调用是否首先来自查询 VBA

vba - 列出在两个单元格中指定范围的范围内的所有数字 - vba

javascript - Excel 任务 Pane 应用程序中矩阵绑定(bind)的最大数据大小是多少?

html - 在vba selenium中循环没有id的无序列表

无法在具有相同功能的 c 和 excel 中得到相同的答案

image - 将范围导出为图像

excel - 使用列标题的自动求和列

vba - 使用 VBA 锁定 Excel 中的行

excel - 使用范围公式时缺少下拉值

events - Worksheet_Change 永远不会触发