当前位置:网站首页>VBA:获取指定数值在指定一维数组中的位置
VBA:获取指定数值在指定一维数组中的位置
2022-08-10 09:40:00 【用户9949496】
文章背景:在采用VBA抓取数据时,有时需要判断指定数值是否在一维数组中已存在;如果存在,则希望能够获取该数值在数组内的位置。
在实践过程中发现,VBA的filter函数无法完全匹配指定数值;而借助Excel的match函数,可以实现完全匹配。接下来分别对Filter函数和Match函数进行介绍。
- Filter 函数
根据指定的筛选准则,传回包含字串阵列子集的以零为基础的阵列。
Filter ( sourcearray , match , [ include , [ compare ]])
- sourcearray 必要项目。要搜寻的字串的一维阵列。
- match 必要。要搜寻的字串。
- include 选用。指出是否传回包含或排除match的子字串的布尔值。若include为True,Filter则会传回包含match作为子字串的阵列子集。若include为False,Filter则会传回不包含match作为子字串的阵列子集。
- compare 选用。指出要使用的字串比较种类的数值。
- compare引数可具有以下的值:
vbBinaryCompare选项,区分大小写;vbTextCompare选项,不区分大小写。默认采用的是vbBinaryCompare选项。
应用示例:
判断某字符串是否在一维数组内存在。
由上图可以看出,采用Filter函数匹配到的是包含A-1的所有元素。而在实际案例中,可能希望只获得完全匹配的元素。
- WorksheetFunction.Match 方法
傳回項目在陣列中的相對位置,其符合指定順序中的指定值。
WorksheetFunction.Match(Arg1, Arg2, Arg3)
如果 match_type 是 0,相符項目會尋找第一個完全等於 lookup_value 的值。
如果 match_type 是 1,相符項目會找到小於或等於 lookup_value 的最大值。
如果省略 match_type,則會假設其值為 1。
应用示例:
Option Explicit
Option Base 1
Sub test()
Dim data(4) As String, temp As String, flag As Integer
data(1) = "A-1"
data(2) = "A-2"
data(3) = "A-3"
data(4) = "A-11"
temp = "A-1"
On Error Resume Next
flag = WorksheetFunction.Match(temp, data, 0)
If Err.number = 0 Then
MsgBox flag
End If
End Sub运行上述程序,得到flag的值为1。
参考资料:
[1] Filter 函数(https://ddz.red/m4Yby)
[2] WorksheetFunction.Match 方法(ttps://ddz.red/Vj4pR)
边栏推荐
猜你喜欢

微信小程序--》小程序生命周期和WXS使用
![[Data Architecture] Distributed Data Grid as a Solution for Centralized Data Monolith](/img/99/b22268e3e47db9e9caad58722e8709.png)
[Data Architecture] Distributed Data Grid as a Solution for Centralized Data Monolith

在“企业通讯录”的盲区,融云的边界与分寸

【Enterprise Architecture】Agile and Enterprise Architecture: Strategic Alliance

09 【Attributes继承 provide与inject】

91.(cesium之家)cesium火箭发射模拟

用高质量图像标注数据加速AI商业化落地

FPGA时钟篇(二) 7系列clock region详解

06 【生命周期 模板引用】

【API 管理】什么是 API 管理,为什么它很重要?
随机推荐
【Prometheus】Node Exporter常用查询PromQL 语句大总结
多线程浅谈
FPGA的虚拟时钟如何使用?
[Metaverse Omi Says] Listen to how Rabbit Fan Rabbit creates a new era of trendy play from virtual to reality
原型和原型链
CAD to WPF: Tips on converting CAD drawing files to WPF vector code files (xaml files)
【数据库架构】OLTP 和 OLAP:实际比较
Message Queuing Overview
Singleton pattern base class
绘制温度曲线图;QChart,
LCD模块如何建立联系分析
【物联网架构】最适合物联网的开源数据库
「应用架构」TOGAF建模:企业可管理性图
【分布式】资源与事务:可观测性的基本二重性
Hugo NexT主题升级记录
武功修炼:内功
Tencent releases the second-generation version of the quadruped robot Max, which completes jumps and somersaults on the plum blossom pile
Flink部署 完整使用 (第三章)
SQL优化总结
【Software Exam System Architect】Case Analysis ⑥ Web Application System Architecture Design