How to Set Maximum Length in a ComboBox

Applies To

OS:
VB:
NT, 9x, 2000
5, 6

TextBox has a MaxLength property.  Unfortunately, ComboBox doesn't.  Here is how to get around this problem.  To set the maximum length simply call SetComboBoxMaxLength with the handle of the parameter (Combo1.hWnd) and the MaxLength of your choice.  To remove the maximum length afterward, call SetComboBoxMaxLength with MaxLength parameter of 0.

Add the following to a .cls, .frm or .bas file

Option Explicit

'general declarations
Private Const CB_LIMITTEXT& = &H141
Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" _
         (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As _
         Integer, ByVal lParam As Any) As Long

'call this procedure to set or remove the maximum lengths for the ComboBox
Public Sub SetComboBoxMaxLength(hWnd As Long, MaxLength As Long)
    SendMessage hWnd, CB_LIMITTEXT&, MaxLength, 0&
End Sub
	
Example

'Set Maximum Length to 10 characters
SetComboBoxMaxLength Combo1.hWnd, 10

'Remove Maximum Length - this will allow the user to type as many characters as desired
SetComboBoxMaxLength Combo1.hWnd, 0