Excel VBA-使用列变量设置范围

Excel VBA-使用列变量设置范围,excel,vba,Excel,Vba,我输入了一段代码来按名称查找列,我想在代码的后面使用这个变量 ColTax = Application.Match("Tax", Sheets("DATA").Rows(1), 0) 但是,我在更新以下范围时遇到问题: Set rng = Range("I3", Range("I" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible) 如何更新“

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

ColTax = Application.Match("Tax", Sheets("DATA").Rows(1), 0)
但是,我在更新以下范围时遇到问题:

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

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

使用
单元格
而不是
范围
,因为
单元格
接受数字列索引

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 Next
On Error GoTo 0
一起括起来,然后测试
,如果不是,则rng为Nothing

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

If Not rng Is Nothing Then
    ' keep processing
End If