excel - 比较 VBA 中的两个数字
问题描述
我正在尝试比较 2 个 3 位数字。这是我当前使用嵌套 Ifs 的代码
If Mid(Num1, 1, 1) = Mid(Num2, 1, 1) Then
'Check first number against first number
If Mid(Num1, 2, 1) = Mid(Num2, 2, 1) Then
'Check second number against second number
If Mid(Num1, 3, 1) = Mid(Num2, 3, 1) Then
'Check third number against third number
Digits = 3
Else
Digits = 2
End If
而这只是其中的一小部分。另外,我还需要检查它们匹配的顺序。因此,无论是完全匹配,所有 3 位数字都以任意顺序匹配,或者 1 位或 2 位数字以任意顺序匹配。
问题是我有很多使用这种方法的 If 语句,因为我必须比较每个数字组合以检查 1 位、2 位、3 位等是否匹配。有没有更好的办法?
解决方案
可以简化为function
一个简单的for
循环
Private Function digitMatch(ByVal num1 as String, ByVal num2 as String) As Byte
' num1 and num2 are strings, because of presumption they can start with 0
' (i.e. 042 is valid 3 digit number format, otherwise they can be integers as well)
Dim i As Byte
Dim matches As Byte: matches = 0
For i = 1 To Len(num1)
If InStr(1, num2, Mid(num1, i, 1)) <> 0 Then
matches = matches + 1
End If
Next i
digitMatch = matches
End Function
所以例如。
digitMatch(023, 053)
将返回2
或digitMatch(123, 321)
将返回3
推荐阅读
- html - 我想将徽标移动到左侧导航到右侧并将两侧分开?
- sql - 将两个 sql 查询合二为一,从 SEDE 的单个表中获取最流行的问题和答案
- javascript - 洗牌列 2d 数组 javascript/typescript
- tkinter - Tkinter Combox 选中的字母一次
- php - Laravel - 从模型关系中急切加载
- java - Spring Boot 微服务,端口黑名单/排除列表
- xpath - xpath 选择的输出与我在浏览器中看到的不同
- javascript - 如何在反应js中呈现只有url的数组?
- elasticsearch - Elasticsearch 至少拥有 1 种事件类型的用户数量
- html - 如何利用 ul 和 li 元素来允许多个正确对齐的列,其中每列并不总是有值