在Excel中插入行之间的“数组”
我有下面的macros插入每个备选行上的数据数组。
这很好,但是,我的数据总是在变化,所以它不是最好的方法。
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的范围?
假设您的请求是将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
(在使用Range
, Cells
等时,正确地限定你所指的是哪个表格,将会在以后避免很多错误。)