为什么不能使用创建的变量来指定工作簿和范围表?”?

时间:2019-07-12 19:59:59

标签: excel vba worksheet

我创建了一个辅助变量,以便当我从工作簿中引用工作表时对我来说更容易。但这是行不通的。

这会产生“错误91”。

“ LastRow1 ...”行高亮显示,如果我删除该行代码,则“ If wb1.Cells(6,10).Value ...”行高亮显示。

我认为是因为“ wb1”。

Sub test()
  Dim wb1 As Worksheet
  Dim LastRow1 As Long
  Dim lag_lead As String

  Set wb1 = Workbooks("name.xlsm").Sheets("sheet1")

    LastRow1 = wb1.Range("D6").End(xlDown).row
    If wb1.Cells(11, 7).Value = -4 Then lag_lead = "4"
    Else: lag_lead = "5"
    End If
End sub

1 个答案:

答案 0 :(得分:0)

sht替换为wb1,并替换为您想要的字母和字母

'Using Find Function
  LastRow = sht.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

'Using SpecialCells Function
  LastRow = sht.Cells.SpecialCells(xlCellTypeLastCell).Row

'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