How to Compare User-Defined Type Variables in Visual Basic

ID: Q88551


The information in this article applies to:
  • Microsoft Visual Basic Standard and Professional Editions for Windows, versions 2.0, 3.0
  • Microsoft Visual Basic programming system for Windows, version 1.0


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.

Additional query words: 2.00 3.00 3.10

Keywords :
Version :
Platform :
Issue type :


Last Reviewed: September 3, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.