VBA 务实

VBA 实现数据查找

2019-04-06  本文已影响0人  Creator_蔚蓝

在 VBA 编程日常中,经常会遇到查找数据的需求。这时,我们第一时间会想到调用 Vlookup 函数来实现。但是,在 VBA 中调用 Vlookup 函数时,会遇到一个问题就是当数据不存在时,就会中断程序的运行,弹出一个错误框。这个错误无法被 VBA 捕捉到,你不能在程序里面作出相应的处理,体验很不好。

为了避免程序被弹出的错误框所中断,我不得不写了如下一个自定义函数来实现 Vlookup 的功能:

  Private Function SuperVLookup(ByRef shSource As Worksheet, _
                             ByVal LookForValue As String, _
                             ByVal ColNumCheck As Integer, _
                             ByVal ColNumReturn As Integer, _
                             ByVal DefaultValue As String) As String
      With shSource
          'Set the default value
          SuperVLookup = DefaultValue
          
          Dim iRow As Long
          Dim rowCount As Long
        
          rowCount = .UsedRange.Rows.count
          For iRow = 2 To rowCount
              If .Cells(iRow, ColNumCheck).Value = LookForValue Then
                  SuperVLookup = .Cells(iRow, ColNumReturn).Value
                  Exit For
              End If
          Next iRow
        End With
End Function

以下是它的参数说明:




更多 UiPath 相关的资讯,请关注公众号:UiPath教程
由于简书禁止直接在文章中插入公众号二维码,请点击 这里 了解添加该公众号的细节。

上一篇 下一篇

猜你喜欢

热点阅读