在VBA中表示要在字符串数组中搜索的负值

问题描述 投票:1回答:1

下面的代码将范围“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
arrays vba string loops range
1个回答
1
投票

一般“IsInArray”功能

如果任何类型化元素是数组的一部分,函数“IsInArray”通常必须检查。

使用Application.Match实施:

  • IsInArray = IsNumeric(Application.Match(ToBeFound, WithinArray(), 0))
  • 使用数字和文本(不区分大小写)
  • 比较全文,但接受*和?也
  • 如果元素是数组的一部分,则Application.Match返回其位置(数字)。如果不是,则返回非数字错误,因此IsNumeric返回False

使用Filter实施:

  • IsInArray = (UBound(Filter(WithinArray(), ToBeFound, True, vbTextCompare)) > -1)
  • 使用数字和文本(可选择区分大小写)
  • 总是比较文本部分,所以“A”将在数组中(“ABC”,“DEF”)
  • 如果元素是数组的一部分,则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)
© www.soinside.com 2019 - 2024. All rights reserved.