美文网首页VBA 务实
VBA 实现数据查找

VBA 实现数据查找

作者: Creator_蔚蓝 | 来源:发表于2019-04-06 17:49 被阅读0次

在 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

以下是它的参数说明:


  • shSource 目标工作表
  • LookForValue 查找的值
  • ColNumChec 超找的列号
  • ColNumReturn 返回值的列号
  • DefaultValue 当查找的值没有被找到时,返回的默认值


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

相关文章

网友评论

    本文标题:VBA 实现数据查找

    本文链接:https://www.haomeiwen.com/subject/zzariqtx.html