简体   繁体   中英

VBA - Excel TextBox1 assign object to varaible

I get error when I try to assign TextBox1 to variable X.

Sub TB1()
   Dim X As TextBox
   Dim Y As String
   X = TextBox1
   If Len(X) < 4 Then
     Y = X
     Do
        Y = "0" & Y
     Loop Until Len(Y) >= 4
     X = Y
   End If
End Sub

You've got a few issues. See comments for details in the code

Sub TB1()
   Dim X As TextBox
   Dim Y As String

   Set X = Me.TextBoxes("Textbox 1")   
   'You need to have some sort of reference to get to the textbox.  
   'Me in this case is a worksheet object I tested in the Sheet1 module.  
   'It has a collection of textboxes which you can refer to by name.  Click on your textbox in excel to see the name in the upper left corner.
   'The `Set` syntax is necessary for objects 

   If Len(X.Text) < 4 Then
     Y = X.Text 
     'Have to explicitly refer to the text in the textbox since it has other properties you can change like height and width
     Do
        Y = "0" & Y
     Loop Until Len(Y) >= 4
     X.Text = Y 'Explicitly refer to the textbox text again to reassign
   End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM