繁体   English   中英

VBA - 使用列变量设置范围

[英]VBA - set Range using column variable

我输入了一段代码来按名称查找列,我想稍后在代码中使用这个变量。

ColTax = Application.Match("Tax", Sheets("DATA").Rows(1), 0)

但是,我在更新以下范围时遇到问题:

Set rng = Range("I3", Range("I" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)

如何更新“我”以反映 ColTax?

使用Cells而不是Range ,因为Cells接受数字列索引。

Dim ColTax As Variant ' Application.Match can return an error, so must be a Variant
ColTax = Application.Match("Tax", Sheets("DATA").Rows(1), 0)

If IsError(ColTax) Then
    ' The match failed, so ColTax is an error, not the column number
    Exit Sub
End If

With Sheets("Data")
    Set rng = .Range(.Cells(3, ColTax), .Cells(.Rows.Count, ColTax).End(xlUp)).SpecialCells(xlCellTypeVisible)
End With

请注意,如果没有可见单元格, SpecialCells(xlCellTypeVisible)将引发错误。 最安全的方法是将Set rng行与On Error Resume NextOn Error GoTo 0括起来,然后测试If not rng Is Nothing

On Error Resume Next
Set rng = ....
On Error GoTo 0

If Not rng Is Nothing Then
    ' keep processing
End If

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM