[英]Count rows in variable range in Excel
我在Excel VBA中建立了一個偏離數據集中兩個值位置的范圍。 范圍中開始和結束的行號將隨數據輸入而變化,因此我需要創建一個始終會偏離設置區域的范圍。 現在,我需要計算范圍內的行/值的數量,以便在復制范圍內的數據后,就可以刪除重復項而無需更改原始列表。 如何計算我范圍內的行數?
我試圖使用copyrange.Rows.Count
但收到錯誤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
使用Range.Find方法后,您始終需要測試是否找到了一些東西:
Set BotRow = Cells.Find("Stud ID")
If BotRow Is Nothing Then
MsgBox "Stud ID was not found!"
Exit Sub
End If
LookAt
參數,否則Excel使用之前(用戶或VBA)使用的任何參數。 Cells
和Range
對象指定它們所在的工作表。 Option Explicit
並正確聲明所有變量。 以下應該工作:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.