VBAdynamic改变“拉斯特罗”

我正试图dynamic更改基于macros正在运行的工作表上的“lastrow”。 目前我正在使用两张纸。 Sheet1有大约150行数据,而Sheet2只有2个。我预料当我selectSheet2并设置lastrow时,它将从Sheet2中获取行数,而不是存储sheet1中的行数。 任何想法如何我可以调整呢?

当前代码:

sub row_count() dim lastrow as long lastrow = Range("A" & Rows.Count).End(xlUp).row if lastrow = 150 then with sheets("sheet2") .select lastrow = Range("A" & Rows.Count).End(xlUp).row msgbox lastrow '<----- Always returns the value of sheet1 instead of sheet2. end with end sub 

您正在使用With块 ,这意味着程序将“With”和“End With”之间的任何内容视为您在关键字“With”之后放置的任何内容的前缀,因此仅针对sheet2修改代码:

 Sub row_count() Dim lastrow As Long lastrow = Sheets("sheet2").Range("A" & Rows.Count).End(xlUp).Row If lastrow = 150 Then With Sheets("sheet2") ' .Select = Sheets("sheet2").Select .Select ' .Range = Sheets("sheet2").Range lastrow = .Range("A" & Rows.Count).End(xlUp).Row MsgBox lastrow End With End Sub 

如果您希望代码在当前可见的工作表上运行,则应将其更改为使用ActiveSheet属性:

 Sub row_count() Dim lastrow As Long lastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row If lastrow = 150 Then With ActiveSheet ' use the currently visible sheet .Select lastrow = .Range("A" & Rows.Count).End(xlUp).Row MsgBox lastrow End With End Sub 

但是,有一些方法可以改善这个代码:为了灵活性,您可以将工作表作为parameter passing。 另外,如果最后使用的行中已经有数据,你的End函数可能会返回第一个使用的行(这与点击最后一行并按下Ctrl +向上箭头相同,所以你应该从下面的单元格开始)。 最后,你不需要select工作表来获得最后一行:

 Sub GetRowCounts() row_count Sheets("sheet1") row_count Sheets("sheet2") End Sub 

 Sub row_count(ws As Worksheet) Dim lastrow As Long lastrow = ws.Range("A1000000").End(xlUp).Row MsgBox lastrow End Sub 

我认为这些例子是最容易遵循的。

 Sub FindingLastRow() 'PURPOSE: Different ways to find the last row number of a range 'SOURCE: www.TheSpreadsheetGuru.com Dim sht As Worksheet Dim LastRow As Long Set sht = ThisWorkbook.Worksheets("Sheet1") 'Ctrl + Shift + End LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'Using UsedRange sht.UsedRange 'Refresh UsedRange LastRow = sht.UsedRange.Rows(sht.UsedRange.Rows.Count).Row 'Using Table Range LastRow = sht.ListObjects("Table1").Range.Rows.Count 'Using Named Range LastRow = sht.Range("MyNamedRange").Rows.Count 'Ctrl + Shift + Down (Range should be first cell in data set) LastRow = sht.Range("A1").CurrentRegion.Rows.Count End Sub 

https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba

保持开放的心态,有很多方法可以做同样的事情。