这可能会或可能不会被要求。
我正在尝试使用宏将一个单元格范围从一个工作表复制到另一个工作表。我遇到的问题是,每次运行宏时,我想要复制的范围都会有很大差异。
例如,我想在第一次运行时复制范围(“A2:P64”),然后当我再次运行数据时,范围的开始仍为A2,但范围的结束可能是P25或p90000。它总是列P和(x变量)行。
我尝试过这样的事情:
Dim past As Worksheet
Dim countHist As String
Dim view As Worksheet
Dim countView As String
Set view = ThisWorkbook.Worksheets("BlueSteel Errors")
Set past = ThisWorkbook.Worksheets("Historical")
countView = view.Cells(Rows.Count, "A").End(xlUp).Row
countHist = past.Cells(Rows.Count, "A").End(xlUp).Row
MsgBox ("P" & countView) ' This currently gives the count of 53, so output is P53
view.Range("A2:P & countView").Select ' THIS IS THE PROBLEM LINE.. should look
'should resemble view.Range("A2:P53").Select
'EVERYTHING ELSE APPEARS TO WORK
Selection.Copy
past.Select
Range("A" & countHist).Select
ActiveSheet.Paste
我找不到确定文本存在的最后一行的方法,然后将该数字附加到Range字段的末尾,这样我就可以选择并附加到另一个工作表..我只需要A2中的数据 - Px不是P以外的所有多余字段。也许我需要复制然后删除它。
答案 0 :(得分:0)
您需要End(xlUp)
功能。
所以更新你有问题的一行
这
view.Range("A2:P & countView").Select ' THIS IS THE PROBLEM LINE..
到
view.Range("A2:" & view.Range("P" & Cells.Rows.Count).End(xlUp).Address).Select
答案 1 :(得分:0)
请...请......请...请...请...请...请...请...请...请...请...请...请...请......请......请......请......请......不要使用.Select
INTERESTING READ
您的代码中还有一些错误
countHist
和countView
声明为String
。它应该是Long
"A2:P & countView"
是一个字符串。您需要"A2:P" & countView
1
添加到目标表的最后一行,这样才不会覆盖最后一行。试试这个
Sub Sample()
Dim past As Worksheet, view As Worksheet
Dim countHist As Long, countView As Long
Set view = ThisWorkbook.Worksheets("BlueSteel Errors")
Set past = ThisWorkbook.Worksheets("Historical")
countView = view.Cells(view.Rows.Count, "P").End(xlUp).Row
countHist = past.Cells(past.Rows.Count, "A").End(xlUp).Row + 1
'~~> Do a direct copy paste instead of selecting first
view.Range("A2:P" & countView).Copy past.Range("A" & countHist)
End Sub
您可能需要使用.Find
来查找最后一行并非所有单元格都填充在特定行中。有关查找最后一行HERE