简体   繁体   中英

How to copy dynamic range in Excel Sheet using vba

我试图在宏中使 rang 是动态的,而不指定最后一行x.Sheets("SheetName").Range("A2:K1000").Copy在 1000 行中x.Sheets("SheetName").Range("A2:K1000").Copy我想将其更改为动态,因为有时我有少于或多于那个。

Try this:

Sub Test() 
Dim lRow as Long 
Dim sht as Worksheet
Set sht = x.Sheets("SheetName")

lRow = sht.Cells(sht.Rows.Count, 2).End(xlUp).Row

sht.Range("A2:K" & lRow).Copy
End Sub

Something like this will do the job:

Option Explicit

Public Sub TestMe()

    Dim lngLastRow As Long

    lngLastRow = 150
    'or come up with a function from here
    'https://www.rondebruin.nl/win/s9/win005.htm

    With x.Worksheets("SheetName")
        .Range(.Cells(2, 1), .Cells(lngLastRow, 1)).Copy
    End With

End Sub

In general, last row in a given column or last column in a given row is something, that you will do quite a lot of time in VBA. Thus, it is a good idea to read this: https://www.rondebruin.nl/win/s9/win005.htm

Typically, look for the last row containing a value from the bottom up.

with x.Sheets("SheetName")
    .Range(.cells(2, "A"), .cells(.rows.count, "K").end(xlup)).Copy
    'paste it somewhere
end with

Is there a way to do this without using copy paste? eg "Set rng = .Range(.Cells(2, 1), .Cells(lngLastRow, 1))" and then making your destination range first cell equal to this variable - eg "rng2 = rng"? I need to perform a multitude of these operations across the same as well as multiple other worksheets in separate workbooks and then need to put these ranges into a master worksheet.

I'm trying to convert my copy paste functions that are using this configuration to what I am describing above, but I can't seem to get it to work.

Thanks.

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