VBA范围问题 – 设置和dynamic
更新:只需要学习如何使fullrngdynamic
大图:我试图根据列中的数据自动创build命名范围。
我发布的子过程将数组的元素作为参数。 所有的这种逻辑工作正常..我可以创build数组的每个元素的命名范围。
我想出了如何在我的范围内获得我想要的值的逻辑。
对于rownum = 2将下一行敲定
包含这个逻辑。
问题是,我有问题的范围。
如果我不使用设置范围=范围(单元格),那么我得到一个对象的错误..这是有道理的,对象已被宣布,但没有设置任何东西。
我只是不知道如何获得这些范围初始化,然后将其更改为我想要的单元格组
fullrng还需要dynamic的将是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 temprng = Range(thiscell, nextcell)
thiscell
和nextcell
已经是range了。 你应该使用Union
来结合他们:
set temrange=application.union(thiscell, nextcell)
用同样的方法改变这个部分:
set fullrange=application.union(fullrng,temprange)
作为一个改进,你必须始终确保在取消Union
之前,你正在合并的两个范围都被定义( is not nothing
)
例如,第一次执行上面的行,全量可能是什么都不会抛出错误,为了避免这样做:
if not fullrange is nothing then set fullrange=application.union(fullrng,temprange) else set fullrange=temprange end if
结果发现有很多问题!
我想这就是当你不创build自己的对象时得到的,你必须探索并找出对象模型。
除了一些明显的错误—使用Cells.Column而不是我的ColumnVar&rownumvariables,下面是我改变了:
我原本是将我的范围设置为随机单元格,以便我可以命名我的范围。 fullrng.Name = TableName我设置完成之后,我刚把这一行移到了右边。
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 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 & rownum, ColumnVar & rownum) Set nextcell = Range(ColumnVar & rownum + 1, ColumnVar & rownum + 1) 'union the range to include all past matching values If thiscell.Text = nextcell.Text Then Set temprng = Application.Union(thiscell, nextcell) If Not fullrng Is Nothing Then Set fullrng = Application.Union(fullrng, temprng) fullrng.Name = TableName Else Set fullrng = temprng End If End If End If Next rownum End If End Sub