How to Compare User-Defined Type Variables in Visual Basic (88551)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 2.0
  • Microsoft Visual Basic Standard Edition for Windows 3.0
  • Microsoft Visual Basic Professional Edition for Windows 2.0
  • Microsoft Visual Basic Professional Edition for Windows 3.0
  • Microsoft Visual Basic Standard Edition for Windows 1.0

This article was previously published under Q88551

SUMMARY

The relational operators (=, <>, and so on) do not support the comparison of user-defined type variables. However, you can compare user-defined type variables by converting the variables to strings, and then comparing the strings. The Windows version 3.1 API hmemcpy can be used to convert a user-defined type variable to a string.

The hmemcpy API was introduced in Microsoft Windows version 3.1, so this technique requires Windows version 3.1 or later.

MORE INFORMATION

If you attempt to compare user-defined type variables using the relational operators, the error "Type mismatch" is displayed.

The following steps demonstrate how to compare user-defined type variables by first converting the variables to strings and then comparing the strings by using the relational operators.

Step-by-Step Example

  1. Start Visual Basic or from the File menu, choose New Project (ALT, F, N) if Visual Basic is already running. Form1 is created by default.
  2. Enter the following code into the global module:
       Type myType
          f1 As String * 2
          f2 As Single
       End Type
    
       ' Enter the following Declare statement entirely as one, single line:
       Declare Sub hmemcpy Lib "kernel" (hpvDest As Any, hpvSource As Any,
          ByVal cbCopy As Long)
    						
  3. Enter the following code into the general Declarations section of Form1:
       ' type2str converts a user-defined type variable to a string.
       Function type2str (t As myType) As String
          Dim s As String
          s = Space$(Len(t))
          Call hmemcpy(ByVal s, t, Len(t))
          type2str = s
       End Function
    						
  4. Enter the following code into the Form1 Click event procedure:
       Sub Form_Click ()
          Dim x As myType
          Dim y As myType
    
          x.f1 = "ab"
          x.f2 = 2
          y = x
    
          If type2str(x) = type2str(y) Then
             Print "x = y"
          Else
             Print "x <> y"
          End If
    
          y.f1 = "ba"
          If type2str(x) > type2str(y) Then
             Print "x > y"
          Else
             Print "x <= y"
          End If
       End Sub
    						
  5. Press the F5 key to run the program.
The program prints "x = y" and "x <= y" on Form1.

Modification Type:MajorLast Reviewed:12/12/2003
Keywords:KB88551