简体   繁体   中英

Insert a range of cells instead of inserting entire row

I have the following code:

If strSheetDate < strFileNameDate Then
    With WS1
        .Rows(2).Insert Shift:=xlDown
        .Cells(2, 1).Value = strFileNameDate
        .Cells(2, 2).Value = WS3.Cells(2, 2).Value
        .Cells(2, 3).Value = .Cells(1, 11).Value
        .Cells(2, 4).Value = WS3.Cells(3, 2).Value
        .Cells(2, 5).Value = .Cells(1, 13).Value
    End With      
End If

and i would like to swap the line:

.Rows(2).Insert Shift:=xlDown

to something where it only moves columns A to E down as I'd like to use the rest of the sheet for more data but don't want it to move down everytime this code is run.

cheers

EDIT Solution :

Thanks to the 2 users below I now have the following 2 sets of code, this one is for a simple insert:

If strSheetDate < strFileNameDate Then

    With WS1
        .Range("A2:E2").Insert shift:=xlDown
        .Cells(2, 1).Value = strFileNameDate            
        .Cells(2, 2).Value = WS3.Cells(2, 2).Value
        .Cells(2, 3).Value = lngAuthormax               
        .Cells(2, 4).Value = WS3.Cells(3, 2).Value
        .Cells(2, 5).Value = lngConsumermax             
    End With
End If

and the second is inserting off of a cell in a range:

iRow2 = WS1.Cells(Rows.Count, 1).End(xlUp).Row
Set rngSheetDate2 = WS1.Range("A2:A" & iRow2)

For Each cell In rngSheetDate2
    If cell.Value > strFileNameDate And cell.Offset(1, 0).Value < strFileNameDate Then
        WS1.Range(cell.Offset(1, 0), cell.Offset(1, 4)).Insert Shift:=xlDown, _
        CopyOrigin:=xlFormatFromLeftOrAbove
        cell.Offset(1, 0).Value = strFileNameDate
        cell.Offset(1, 1).Value = WS3.Cells(2, 2).Value
        cell.Offset(1, 2).Value = lngAuthormax
        cell.Offset(1, 3).Value = WS3.Cells(3, 2).Value
        cell.Offset(1, 4).Value = lngConsumermax
        Exit For
    End If
Next

Thank you

尝试这个:

.Range(.cells(2, 1), .cells(2, 5)).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM