简体   繁体   English

VBA-Excel TextBox1将对象分配给变量

[英]VBA - Excel TextBox1 assign object to varaible

I get error when I try to assign TextBox1 to variable X. 尝试将TextBox1分配给变量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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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