简体   繁体   中英

Method “Range” of object _worksheet failed when searching for lastrow VBA Excel

So here is my second question to you experts. I am trying to find the last row of a column, but I keep on getting the "method range of object worksheet failed.

I have tried changing the syntax to various things but I still can't work it out.

I am new to VBA excel and I would really appreciate your help with this one.

Thank you. The offending line is marked with ********

Private Sub GetProductCode()
'Opens jobs file
'Trims down customer reference column to job number only, then searches job file to return product code
Dim sJobNumber As String
Dim sCustomerReference As String
Dim wsRevRownum As Long
Dim wbkJobs As Workbook
Dim wsJobs As Worksheet
Dim wsRev As Worksheet
Dim strPathFile As String
Dim strSearch As String
Dim fCell As Range
Dim fCellRowNum As String
Dim wsJobsLastrow As Long
Dim wsRevLastrow As Long


'On Error GoTo ErrHandler
Application.ScreenUpdating = False

'Change as desired
    strPathFile = "\\ACHILLES\Company\Production_schedule\Jobs.xlsm"
    strSearch = "Specific text"

 Set wbkJobs = Workbooks.Open _
              (Filename:=strPathFile, _
              UpdateLinks:=0, _
              ReadOnly:=True, _
              AddToMRU:=False)

 Set wsRev = ThisWorkbook.Sheets(3)
 MsgBox wsRev.Name

 Set wsJobs = wbkJobs.Sheets("Jobs")

'MsgBox wbkJobs.Name
 wsRevRownum = 2

With wsRev
 wsRevLastrow = wsRev.Range("E" & Rows.Count).End(xlUp).Row ********
End With

With wsJobs
 wsJobsLastrow = wsJobs.Range("A" & Rows.Count).End(xlUp).Row
End With


'Loop through revenue file and search for entries in jobs file. If found then take the product code from the jobs file and populate revenue file
Do Until wsRev.Range("E" & wsRevRownum).Address = (wsRevLastrow + 1)
    'initialise variables
    sCustomerReference = ""
    sJobNumber = ""
    strSearch = ""

Try one of these if you are looking for the last row in a worksheet:

Sub GetLastRow()

'Different ways to find the last row number of a range

Dim ws As Worksheet
Dim LastRow As Long

Set ws = ThisWorkbook.Worksheets("Sheet1")

'Ctrl + Shift + End
  LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

'Using UsedRange
  ws.UsedRange 'Refresh UsedRange
  LastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row

'Using Table Range
  LastRow = ws.ListObjects("Table1").Range.Rows.Count

'Using Named Range
  LastRow = ws.Range("MyNamedRange").Rows.Count

'Ctrl + Shift + Down (Range should be first cell in data set)
  LastRow = ws.Range("A1").CurrentRegion.Rows.Count

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM