Advertisement
7_2009-2012 VB function enhancement #231755

Safe UBound and LBound

Ever wanted to use LBound and UBound to get arrays boundaries without jumping over error message when the array is empty? These functions will replace the ordinary LBound and UBound procedures so you don’t need to worry about errors. I've also included a way to get the dimensions of an array. Just paste the following code into a module, and the problem is solved.

AI

AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Source Code
original-source
Option Explicit
Declare Function VarPtrArray Lib "msvbvm50.dll" Alias "VarPtr" (Ptr() As Any) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Public Function SafeUBound(ByVal lpArray As Long, Optional Dimension As Long = 1) As Long
  Dim lAddress&, cElements&, lLbound&, cDims%
  If Dimension < 1 Then
    SafeUBound = -1
    Exit Function
  End If
  CopyMemory lAddress, ByVal lpArray, 4
  If lAddress = 0 Then
    ' The array isn't initilized
    SafeUBound = -1
    Exit Function
  End If
  
  ' Calculate the dimensions
  CopyMemory cDims, ByVal lAddress, 2
  Dimension = cDims - Dimension + 1
  
  ' Obtain the needed data
  CopyMemory cElements, ByVal (lAddress + 16 + ((Dimension - 1) * 8)), 4
  CopyMemory lLbound, ByVal (lAddress + 20 + ((Dimension - 1) * 8)), 4
  SafeUBound = cElements + lLbound - 1
  
End Function
Public Function SafeLBound(ByVal lpArray As Long, Optional Dimension As Long = 1) As Long
  Dim lAddress&, cElements&, lLbound&, cDims%
  If Dimension < 1 Then
    SafeLBound = -1
    Exit Function
  End If
  CopyMemory lAddress, ByVal lpArray, 4
  If lAddress = 0 Then
    ' The array isn't initilized
    SafeLBound = -1
    Exit Function
  End If
  ' Calculate the dimensions
  CopyMemory cDims, ByVal lAddress, 2
  Dimension = cDims - Dimension + 1
  
  ' Obtain the needed data
  CopyMemory lLbound, ByVal (lAddress + 20 + ((Dimension - 1) * 8)), 4
  SafeLBound = lLbound
  
End Function
Public Function ArrayDims(ByVal lpArray As Long) As Integer
  Dim lAddress As Long
  
  CopyMemory lAddress, ByVal lpArray, 4
  If lAddress = 0 Then
    ' The array isn't initilized
    ArrayDims = -1
    Exit Function
  End If
  CopyMemory ArrayDims, ByVal lAddress, 2
  
End Function
Original Comments (3)
Recovered from Wayback Machine