[英]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.