كيفية العثور على قيمة في صفيف باستخدام vba؟

عندما تقوم بتخزين القيم في مصفوفة، قد تكون هناك أوقات تحتاج فيها إلى إجراء بحث عن المصفوفة. في هذه الحالة، عليك أن تعرف الطرق التي يمكنك استخدامها. انظر الآن إلى الكود أدناه والذي يمكن أن يساعدك على فهم كيفية البحث عن قيمة في مصفوفة.

العثور على قيمة في صفيف-1
  1. في الجزء الأول من الكود لديك متغيرات تحتاج إلى استخدامها لاحقًا في الكود.
  2. بعد ذلك، الجزء التالي يقوم بإنشاء أرقام عشوائية باستخدام RND للحصول على القيم العشر من المصفوفة.
  3. بعد ذلك، يتيح لك مربع الإدخال إدخال القيمة التي تريد البحث عنها في الجدول.
  4. بعد ذلك، لديك سطر يستخدم عبارة IF للتحقق مما إذا كانت القيمة التي أدخلتها في مربع الإدخال رقمًا أم لا.
  5. في هذا الجزء لديك رمز للسلسلة لاستخدامه في مربع الرسالة إذا لم يتم العثور على القيمة التي أدخلتها.
  6. يستخدم هذا الجزء من التعليمات البرمجية حلقة For (لكل) للتنقل خلال كل عنصر في المصفوفة والتحقق مما إذا كانت القيمة التي أدخلتها موجودة في المصفوفة أم لا.
  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
ما هو فبا

تعرف على المزيد حول جداول VBA