In this session, we dive into the UBound function in VBA, which is essential for determining the largest subscript or index in an array. Building upon the previous session where the LBound function was discussed, we explore how UBound complements LBound by providing the highest index value in a single-dimensional or multi-dimensional array. We'll walk through practical examples to illustrate its usage, including handling arrays of different dimensions.

What will you learn

  • Understanding what the UBound function does in VBA.
  • Differentiating between UBound and LBound functions.
  • Applying the UBound function to single-dimensional arrays.
  • Extending the usage of UBound to multi-dimensional arrays.
  • Modifying UBound function calls based on array dimensions.
  • Practical examples of UBound in action.

Takeaway notes

  • UBound returns the highest index value in an array.
  • For single-dimensional arrays, UBound just requires the array name.
  • For multi-dimensional arrays, UBound requires the array name and the dimension number.
  • Syntax: UBound(arrayName, dimension).
  • In an array of size 5, UBound(arrayName) will return 5.
  • In a two-dimensional array of size 3x2, UBound(arrayName, 1) will return 3, and UBound(arrayName, 2) will return 2.

Practice questions

  1. What does the UBound function do in VBA?
  2. How does UBound differ from LBound in VBA?
  3. Write the VBA code to find the highest subscript in an array named dataArray of size 10.
  4. Given a two-dimensional array matrixArray of size 4x3, what will UBound(matrixArray, 1) return?
  5. How would you modify the UBound function call for a three-dimensional array?
  6. Provide an example where UBound could be used to iterate over an array in VBA.
  7. Explain the output of UBound(arrayExample, 2) for an array of size 5x7.
  8. Can UBound be used for an empty array? Describe the outcome.
  9. Write a VBA function that returns both the lower and upper bounds of a given array.
  10. What will UBound(arrayTest) return for an array arrayTest with values {"Apple", "Banana", "Cherry"}?
  11. How would you handle a scenario where you need to find the largest index value of the third dimension in a 3D array?
  12. Compare the UBound function usage in a one-dimensional array and a two-dimensional array.
  13. Discuss a situation where misinterpreting the UBound output could lead to an error in your VBA code.
  14. How can UBound be helpful when dynamically resizing arrays in VBA?
  15. Write a short VBA script using UBound to print the largest index of each dimension of an array multiArray of size 4x3x2.

Mark Lesson Complete (Mastering the UBound Function in VBA Arrays)