下面的代码将范围“B”和t中的值与x(1)中给出的数组进行比较。我还想包括负值,以便在比较完成时也检测到该范围内的负值。我只是不知道如何在我的数组x(1)中输入“negativ value”。我试过这个“<0”,但没有成功。
sub compare()
dim X(1) as string
dim t as integer
x(1)=("0")
t=2
Do
If IsInArray(ad.Range("B"&t).Value,x) then
'do something
Else: 'do something else
End if
Loop Until ad.Range("A"&t)=""
End sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray=(UBound(Filter(arr,stringToBeFound))>-1)
End Function
一般“IsInArray”功能
如果任何类型化元素是数组的一部分,函数“IsInArray”通常必须检查。
使用Application.Match
实施:
IsInArray = IsNumeric(Application.Match(ToBeFound, WithinArray(), 0))
Application.Match
返回其位置(数字)。如果不是,则返回非数字错误,因此IsNumeric
返回False
。使用Filter
实施:
IsInArray = (UBound(Filter(WithinArray(), ToBeFound, True, vbTextCompare)) > -1)
Filter
返回带有剩余项的过滤数组。由于剩下的数组是从0开始的,所以数组的上限至少为0.如果元素不是它的一部分,那么Ubound
不是0或更高,因此> -1比较。例
如果应将单个单元格内容与预定义数组进行比较:
Private Sub CompareRangeValuesWithGivenArray()
Dim ad As Worksheet
Dim testArray() As Variant
Dim t As Long
Set ad = ActiveSheet
testArray() = Array("0", -3.2, "ABC", 5)
For t = 1 To ad.Cells(ad.Rows.Count, "A").End(xlUp).Row
If IsInArray(ad.Cells(t, "B").Value, testArray()) Then
Debug.Print ad.Cells(t, "B").Value & " is in Array"
Else
Debug.Print ad.Cells(t, "B").Value & " is NOT in Array"
End If
Next t
End Sub
Private Function IsInArray(ByRef ToBeFound As Variant, ByRef WithinArray() As Variant) As Boolean
IsInArray = IsNumeric(Application.Match(ToBeFound, WithinArray(), 0))
End Function
(即使你搜索文本,保持IsNumeric
)
负值
如果负面元素也应该作为IsInArray() = True
返回,那么将Abs()
封装你的“待检查值”并将正值放入你的数组中:
If IsInArray(Abs(ad.Cells(t, "B").Value), testArray()) Then
如果负数元素应该在您的数组中:
testArray(1) = -1
testArray(2) = -2.5
要么
testArray() = Array(1, -2.5)