我有一个宏,可以通过在B列中找到最后一个空行来设置LastRow。但是,有时整个行都是空的,除了标题所在的行1之外。 我需要在LastRow变量上设置IF语句,以说IF范围B2为NULL(或等于0),然后使用B2作为参数来设置LastRow。否则,请通过.End(xlUp)
查找最后一行我已经在我的变量上尝试了不同的IF语句,但都导致了错误消息
Sub WeeklyGL()
'Set Variable Parameters for Monthly Sheet
Dim mySheet As String
Dim LastrowMonth As Integer
Dim mKey As Range
Dim mKeyrng As Range
Dim mValrng As Range
mySheet = Sheets("Weekly_GL").Range("AE1")
LastrowMonth = Sheets(mySheet).Range("B1048576").End(xlUp).Row --> this is where i need help
Set mKey = Sheets(mySheet).Range("AC1")
Set mKeyrng = Sheets(mySheet).Range("AC2:AC" & LastrowMonth)
Set mValrng = Sheets(mySheet).Range("AD2:AD" & LastrowMonth)
最后尝试:LastrowMonth =如果Sheets(mySheet).Range(“ B2”)ISNULL然后.Range(“ B2”)其他Sheets(mySheet).Range(“ B1048576”)。End(xlUp).Row >
答案 0 :(得分:0)
我已经使用工作表引用来清理您的代码:
Option Explicit
Sub Test()
'Set Variable Parameters for Monthly Sheet
'Dim mySheet As String 'instead of this, create a worksheet variable like this:
Dim mySheet As Worksheet
Dim LastrowMonth As Integer
Dim mKey As Range
Dim mKeyrng As Range
Dim mValrng As Range
Set mySheet = ThisWorkbook.Sheets(ThisWorkbook.Sheets("Weekly_GL").Range("AE1")) 'this way you can reference and work cleaner:
With mySheet
LastrowMonth = .Cells(.Rows.Count, 2).End(xlUp).Row 'this is the standard to find the last row
If LastrowMonth = 1 Then LastrowMonth = 2 'this is what you were looking for
Set mKey = .Range("AC1")
Set mKeyrng = .Range("AC2:AC" & LastrowMonth)
Set mValrng = .Range("AD2:AD" & LastrowMonth)
End With
End Sub
Option Explicit
是避免错误的好选择,因为它会迫使您声明所有变量。
使用With
可以引用您正在使用的内容,在这种情况下,mySheet
仅通过使用.