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

时间:2019-04-11 12:34:19

标签: arrays vba string loops range

下面的代码将范围“ B”&t中的值与x(1)中给出的数组进行比较。我还希望包括负值,以便在比较完成时也能检测到该范围内的负值。我只是不知道如何在数组x(1)中输入“负值”。我已经尝试过此“ <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

1 个答案:

答案 0 :(得分: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)