【发布时间】:2017-12-01 18:37:35
【问题描述】:
更新:只需要学习如何使 fullrng 动态化
大图: 我正在尝试根据列中的数据自动创建命名范围。
我发布的子过程将数组的元素作为参数。所有这些逻辑都可以正常工作。我可以为数组的每个元素创建命名范围。
我想出了如何在我的范围内获取我想要的值的逻辑。
for rownum = 2 to finalrow 下一行
包含此逻辑。
问题是我的范围有问题。
如果我不使用 Set my range = Range(cells) 那么我会收到一个对象错误。这是有道理的,对象已被声明但未设置任何内容。
我只是不知道如何初始化这些范围,然后将它们更改为我想要的单元格组
fullrng 也需要是动态的是 2 个单元格高,然后是 3 ,然后是 4,等等。
Sub Createranges(ByVal TableName As String)
If TableName <> "" Then
Debug.Print TableName
Dim fullrng As Range
Dim temprng As Range
Dim thiscell As Range
Dim nextcell As Range
Set fullrng = Range("H1")
fullrng.Name = TableName
For rownum = 2 To finalrow
'Checking to see if cell should be in named range
If Cells(rownum, ColumnVar).Value = TableName Then
'Modify Ranges for union
Set thiscell = Range(ColumnVar & Cells.Row, ColumnVar & Cells.Column)
Set nextcell = Range(ColumnVar & Cells.Row + 1, ColumnVar & Cells.Column)
'union the range to include all past matching values
If thiscell.Value2 = nextcell.Value2(2, 1) Then
Set temprng = Range(thiscell, nextcell)
'Figure out dynamic ranges here
Set fullrng = Range(
fullrng = Union(fullrng, temprng)
End If
End If
Next rownum
End If
End Sub
【问题讨论】:
-
这样可以吗?
-
如果您要设置范围(即使通过重新分配),您需要使用 Set 关键字。