gpt4 book ai didi

excel - 将 Range.SpecialCells 与错误处理程序一起使用是个好习惯吗?

转载 作者:行者123 更新时间:2023-12-02 16:29:11 24 4
gpt4 key购买 nike

当使用Range.SpecialCells时如果范围不包含与条件匹配的单元格,则会抛出错误,指出未找到单元格。

此问题最常见的解决方案是让它发生并使用错误处理程序来处理它。

这是解决该问题的最有名的方法吗?还是有其他解决方案可能同样好或更好,可以避免使用错误处理程序?

我唯一能想到的就是保存第一个单元格的值,然后将其值更改为与条件匹配的值,这样就可以避免错误,使其始终至少匹配该一个单元格,然后将值更改回其值原始值并检查匹配范围的地址以查看它是否仅匹配一个或多个单元格。

一个糟糕/缓慢的解决方案是根本不使用它,而只是使用带检查的循环。

这里有一些简单的示例代码来演示它如何与错误处理程序一起使用:

Private Sub Procedure()

Dim OriginalRange As Excel.Range
Dim NewRange As Excel.Range

Set OriginalRange = ThisWorkbook.Worksheets(1).Range("A1:C4")
On Error GoTo ErrorHandler
Set NewRange = OriginalRange.SpecialCells(Type:=Excel.XlCellType.xlCellTypeConstants, Value:=Excel.XlSpecialCellsValue.xlNumbers)
Exit Sub
ErrorHandler:
If (VBA.Err.Number <> 1004) Then VBA.Err.Raise VBA.Err.Number

End Sub

最佳答案

是的,使用错误处理程序是完全正常的(我更喜欢这种方式)。我所做的是,将其夹在 On Error Resume NextOn Error GoTo 0 之间,然后检查 If NewRange is Nothing

查看此示例

On Error Resume Next
Set NewRange = OriginalRange.SpecialCells(Type:=Excel.XlCellType.xlCellTypeConstants, _
Value:=Excel.XlSpecialCellsValue.xlNumbers)
On Error GoTo 0

If NewRange Is Nothing Then
MsgBox "Your message here informing the USER that desired cells were not found"
Else
'
'~~> Do whatever you want with the range
'
End If

关于excel - 将 Range.SpecialCells 与错误处理程序一起使用是个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com