简体   繁体   中英

Count rows in variable range in Excel

I have established, in Excel VBA, a range biased off of the location of two values in a data set. The row numbers of the start and stop in the range will change with data entry so I needed to create a range that will always offset from a set area. I now need to count the number of rows/values in the range so that once I copy the data in the range I can then remove the duplicates without altering the original list. How can I count the number of rows in my range?

I have attempted to use copyrange.Rows.Count but got error 438

Sub count_ID_List()
    Set botrow = Cells.Find("Stud ID")
    'Finds the first row of the count section of the invitory'
    Set toprow = Cells.Find("Stud Part Number")
    'Finds the top row of the company invintory'
    Set copyrange = Range(toprow.Offset(1, 0).Address, botrow.Offset(-12, 1).Address)
    Set copyto = Range(botrow.Offset(1, 0), botrow.Offset(1, 0))
    copyrange.Copy (copyto)
    'this is where i would like to then remove duplicates from the newly copied data'
End Sub

After using the Range.Find method you always need to test if something was found:

Set BotRow = Cells.Find("Stud ID")
If BotRow Is Nothing Then
    MsgBox "Stud ID was not found!"
    Exit Sub
End If
  • Always define the LookAt parameter in the find method otherwise Excel uses whatever was used before (by either a user or VBA).
  • Specify for all Cells and Range objects in which worksheet they are.
  • Use Option Explicit and declare all your variables properly.

The following should work:

Option Explicit

Public Sub count_ID_List()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1") 'define your sheet name here

    'Finds the first row of the count section of the invitory'
    Dim BotRow As Range
    Set BotRow = ws.Cells.Find(What:="Stud ID", LookAt:=xlWhole)
    If BotRow Is Nothing Then
        MsgBox "'Stud ID' was not found!"
        Exit Sub
    End If

    'Finds the top row of the company invintory'
    Dim TopRow As Range
    Set TopRow = ws.Cells.Find(What:="Stud Part Number", LookAt:=xlWhole)
    If TopRow Is Nothing Then
        MsgBox "'Stud Part Number' was not found!"
        Exit Sub
    End If

    Dim CopyRange As Range
    Set CopyRange = ws.Range(TopRow.Offset(1, 0), BotRow.Offset(-12, 1))

    Dim CopyTo As Range
    Set CopyTo = BotRow.Offset(1, 0)

    'output row count
    Debug.Print CopyRange.Rows.Count

    CopyRange.Copy Destination:=CopyTo

    'this is where i would like to then remove duplicates from the newly copied data'
    CopyTo.Resize(RowSize:=CopyRange.Rows.Count).RemoveDuplicates Columns:=Array(1), Header:=xlNo
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