简体   繁体   中英

How to select last three row automatically on a give range in EXCEL VBA

I created a code to select and paste data from one sheet to another. But this code is always selecting last three values in row. I need to select the data based on given range. Eg C5:C15 not for the entire c column. Help me

Private Sub CommandButton1_Click()

Dim LastRow1, LastRow2, LastRow3 As Long
Dim Last3Rows1, Last3Rows2, Last3Rows3 As Range

LastRow3 = Sheets("AVG-PO").Range("C" & Rows.Count).End(xlUp).Row
LastRow1 = Sheets("AVG-PO").Range("A" & LastRow3).End(xlUp).Row
LastRow2 = Sheets("AVG-PO").Range("B" & LastRow3).End(xlUp).Row

Set Last3Rows3 = Sheets("AVG-PO").Range("C" & LastRow3).Offset(-2, 0).Resize(3, 1)
Set Last3Rows1 = Sheets("AVG-PO").Range("A" & LastRow3).Offset(-2, 0).Resize(3, 1)
Set Last3Rows2 = Sheets("AVG-PO").Range("B" & LastRow3).Offset(-2, 0).Resize(3, 1)

Last3Rows1.Select
Selection.Copy Sheets("Data").Range("A30")

Last3Rows2.Select
Selection.Copy Sheets("Data").Range("B30")

Last3Rows3.Select
Selection.Copy Sheets("Data").Range("C30")

End Sub

在此处输入图片说明

Not sure i quite understand what range you want but you might be able to use this.

Sub test()
    Dim NextFree As Long
    Dim TableStartRange As Long

    For i = 1 To 100
    Select Case Range("A" & i).Value
        Case "Table1"
            TableStartRange = i + 1 'finds table1 in A2 and then +1 before the actual table start in column C
    End Select

    NextFree = Range("C" & TableStartRange & ":C" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row ' returns the value 14 since its the first free row in column C

End Sub

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