如何使用vba查找数组中的值?

当您将值存储在数组中时,有时可能需要进行数组查找。在这种情况下,您需要知道可以使用的方法。现在看下面的代码,它可以帮助您了解如何在数组中搜索值。

在数组 1 中查找值
  1. 在代码的第一部分中,您有稍后需要在代码中使用的变量
  2. 之后,下一部分使用RND生成随机数,以从数组中获取十个值。
  3. 接下来,您可以在输入框中输入要在表中搜索的值。
  4. 之后,您有一行使用IF 语句来检查您在输入框中输入的值是否为数字。
  5. 在此部分中,如果未找到您输入的值,您将在消息框中使用字符串的代码。
  6. 这部分代码使用For (For Each) 循环循环遍历数组中的每个元素,并检查您输入的值是否在数组中。
  7. 代码的最后一部分显示一条消息,指示是否找到该值。
 Option Base 1 Sub vba_array_search() 'this section declares an array and variables 'that you need to search within the array. Dim myArray(10) As Integer Dim i As Integer Dim varUserNumber As Variant Dim strMsg As String 'This part of the code adds 10 random numbers to 'the array and shows the result in the 'immediate window as well. For i = 1 To 10 myArray(i) = Int(Rnd * 10) Debug.Print myArray(i) Next i 'it is an input box that asks 'you the number that you want to find Loopback: varUserNumber = InputBox _ ("Enter a number between 1 and 10 to search for:", _ "Linear Search Demonstrator") 'it's an if statement that checks for the value that you 'have entered in the input box. If varUserNumber = "" Then End If Not IsNumeric(varUserNumber) Then GoTo Loopback If varUserNumber < 1 Or varUserNumber > 10 Then GoTo Loopback 'message to show if the value doesn't found. strMsg = "Your value, " & varUserNumber & _ ", was not found in the array." 'loop through the array and match each value with the 'the value you have entered in the input box. For i = 1 To UBound(myArray) If myArray(i) = varUserNumber Then strMsg = "Your value, " & varUserNumber & _ ", was found at position " & i & " in the array." Exit For End If Next i 'message box in the end MsgBox _ strMsg, vbOKOnly + vbInformation, _ "Linear Search Result" End Sub

添加评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注