[英]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.通常,给定列中的最后一行或给定行中的最后一列是您将在 VBA 中花费大量时间的事情。 Thus, it is a good idea to read this: https://www.rondebruin.nl/win/s9/win005.htm因此,阅读以下内容是个好主意: 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"? 例如“设置rng = .Range(.Cells(2,1),.Cells(lngLastRow,1))”,然后使目标范围的第一个单元格等于此变量-例如“ 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. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.