在Excel中的行之间插入“数组”

时间:2016-09-12 01:06:32

标签: excel excel-vba vba

我有下面的宏,它在每个替代行上插入一个数据数组。

这很好用,但是,我的数据一直在变化,所以它不是最好的方法。

Sub inserttexteveryonerow()
    Dim Last As Integer
    Dim emptyRow As Integer
    Last = Range("A" & Rows.Count).End(xlUp).Row
    For emptyRow = Last To 2 Step -1
        If Not Cells(emptyRow, 1).Value = "" Then
            Rows(emptyRow).Resize(1).insert
            Range(Cells(emptyRow, "A"), Cells(emptyRow, "F")).Value = Array("COLA", "COLB", "COLC", "COLD", "COLD", "COLF")
        End If
    Next emptyRow
End Sub

我希望将我的数据放在Sheet1上,但我在Sheet2上的备用插入行有特定数据。

如何编辑此行:

Range(Cells(emptyRow, "A"), Cells(emptyRow, "F")).Value = Array("COLA", "COLB", "COLC", "COLD", "COLD", "COLF")

从插入特定数据到在SHEET2行A1到AF上插入范围?

1 个答案:

答案 0 :(得分:0)

假设您的请求是将Sheet2 的范围从单元格A1插入到单元格F1 ,则以下内容应该有效:

Sub inserttexteveryonerow()
    Dim Last As Integer
    Dim emptyRow As Integer
    Last = Range("A" & Rows.Count).End(xlUp).Row
    For emptyRow = Last To 2 Step -1
        If Not Cells(emptyRow, 1).Value = "" Then
            Rows(emptyRow).Resize(1).insert
            Range(Cells(emptyRow, "A"), Cells(emptyRow, "F")).Value = Worksheets("Sheet2").Range("A1:F1").Value
        End If
    Next emptyRow
End Sub

但是,重写代码以使用With块是个好主意,这样可以更容易地正确识别您所指的表单:

Sub inserttexteveryonerow()
    Dim Last As Integer
    Dim emptyRow As Integer
    With Worksheets("Sheet1")
        Last = .Range("A" & .Rows.Count).End(xlUp).Row
        For emptyRow = Last To 2 Step -1
            If Not .Cells(emptyRow, 1).Value = "" Then
                .Rows(emptyRow).Resize(1).insert
                .Range(.Cells(emptyRow, "A"), .Cells(emptyRow, "F")).Value = Worksheets("Sheet2").Range("A1:F1").Value
            End If
        Next emptyRow
    End With
End Sub

(正确地说明使用RangeCells等时您所指的是哪个工作表,可以防止以后出现很多错误。)