This article was previously published under Q152288
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
There is no built-in function to return the number of dimensions in anarray variable in Microsoft Visual Basic for Applications. The easiest wayto do this is by looping through the dimensions and using an error handlerto return the number of dimensions.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. The easiest way to determine the number of dimensions in a Visual Basic forApplications array variable is to get the routine to attempt a task witheach dimension. When it attempts to do the task to a nonexistent dimension,an error will be returned. An error handler can be used to return thedimension in which the task was last successful. One way to test adimension is by using the LBound function. The LBound function takes twoarguments, the array variable and the specific dimension, and returns thelower bounds of that dimension. Using this function on a nonexistentdimension returns an error. Coupled with an error handler, this can be usedto determine the number of dimensions.
Sample Visual Basic Procedure
This routine tests the array named Xarray by testing the LBound of eachdimension. Using a For...Next loop, the routine cycles through the numberof possible array dimensions, up to 60000, until an error is generated.Then the error handler takes the counter step that the loop failed on,subtracts one (because the previous one was the last one without an error),and displays the result in a message box.
Sub NumberOfDimensions() 'Dimensions Xarray as an array. Dim Xarray(1 to 10, 5 to 20, 256 to 300, 8, -5 to 0) 'Sets up the error handler. On Error GoTo FinalDimension 'Visual Basic for Applications arrays can have up to 60000 'dimensions; this allows for that. For DimNum = 1 to 60000 'It is necessary to do something with the LBound to force it 'to generate an error. ErrorCheck = LBound(Xarray, DimNum) Next DimNum Exit Sub ' The error routine. FinalDimension: MsgBox "The array has " & DimNum - 1 & " dimensions" End Sub
For additional information about getting help with Visual Basic forApplications, please see the following article in the Microsoft KnowledgeBase:
163435 VBA: Programming Resources for Visual Basic for Applications