excel - 在 Excel (VB) 中查找值
问题描述
我正在努力让我的 vb 脚本正常工作。
我需要在数组中找到值 a(string) 和 b(date)。
例子:
[string1][date1] where in arr[[st1][dat1],[st2][dat2],[string1][date1]]
最后一个将匹配 true 第一个和第二个将是 false
价值观:
Function IsInArray(stringToBeFound1 As String, ByVal dateToBefound As Date, arr As Variant) As Boolean
Dim Found1 As Boolean
Dim Found2 As Boolean
Dim x As Integer
Found1 = False
Found2 = False
x = 0
For x = 0 To UBound(arr, 1) // this does not seem to work
If stringToBeFound1 = arr(x, 0) Then
Found1 = True
End If
If dateToBefound = arr(x, 1) Then
Found2 = True
End If
If Found1 = 1 And Found2 = 1 Then IsInArray = True
Next
End Function
用法:=IsInArray(C6,D6,'Sheet2'!C:D)
解决方案
您的代码的主要错误是您提供给函数的参数不是数组。这是一个范围。请阅读下面代码中的更多评论。
Function IsInArray(stringToBeFound As String, _
ByVal dateToBefound As Date, _
Rng As Range) As Boolean
' =IsInArray(C6,D6,'Sheet2'!C:D) ' C:D is a range, not an array
Dim MyRng As Range
Dim Arr As Variant
Dim R As Long ' loop counter: rows
' since there are more than a million rows in a sheet
' and an integer can only count up to abt 32000
' you can't use an Integer to loop through all rows
' Found1 = False ' }
' Found2 = False ' } These values are given by the Dim statements above
' x = 0 ' }
' all the column is too big a range.
' it will take ages to find nothing.
' Exclude blank cells at the bottom:-
With Rng
Set MyRng = Range(.Cells(1), Cells(Rows.Count, .Column).End(xlUp)) _
.Resize(, .Columns.Count)
' ' you may prefer this one, actually:
' Set MyRng = Range(.Cells(2, 1), Cells(Rows.Count, .Column).End(xlUp)) _
' .Resize(, .Columns.Count)
Debug.Print MyRng.Address ' for testing MyRng
End With
Arr = MyRng.Value ' creates a 1-based 2-D array
For R = 1 To UBound(Arr, 1)
' always compare the code-generated variable with the given constant
If Arr(R, 1) = stringToBeFound Then
' ' you may prefer a case-insensitive comparison:-
' If StrComp(Arr(R, 1), stringToBeFound, vbTextCompare) = 0 Then
If dateToBefound = Arr(R, 2) Then
IsInArray = True
Exit For
End If
End If
Next
End Function
我使用下面的代码使用您想要的语法和在 VBA 中将函数作为 UDF 进行了测试。将其用作 UDF 时,我敦促您使用绝对地址引用目标范围,例如Sheet2'!$C:$D
. 不这样做更像是自找麻烦。
Private Sub Test()
' =IsInArray(C6,D6,'Sheet2'!C:D)
Debug.Print IsInArray("B", Date + 1, Sheet2.Columns("C:D"))
End Sub
推荐阅读
- powerbi - 将现有表过滤到另一个表,而不在现有表上添加度量或列
- angular7 - 如何为组件/模板增加 nz-Drawer 的宽度?参考链接是http://ng-zorro.cn/components/drawer/en
- elasticsearch - 如何设置 logstash 配置输出以同时使用 HTTP 和其他 HTTPS 端点?
- excel - 同样定义的变量做同样的事情,但仍然得到 TypeMismatch
- tsql - 如何使用负值 DBCC CHECKIDENT RESEED
- r - dyplr group_by 中的问题
- java - 将 10 个文件与模板文件进行比较
- airflow - 有没有办法提取 Last run (date) ,最后从 Airflow 过期的 DAG 并通过电子邮件发送
- javascript - TypeError 时返回值或 null:无法读取未定义的属性“数据”
- javascript - 我的进口产品哪里出了问题?