从几个文本框(V​​BA)填充列

时间:2013-11-08 12:13:47

标签: excel vba excel-vba

我需要有关VBA脚本的帮助。 我们的老师告诉我们使用:

ListBox1.AddItem ComboBox1.Text And Val(TextBox4.text) And ListBox1.AddItem
FormatCurrency(price, 2)

它应该显示ComboBox1的名称,TextBox4的数量和TextBox5的价格(格式化为'price'变量),但它给我一个错误。

我决定尝试使用:

ListBox1.AddItem ComboBox1.Text  
ListBox1.AddItem Val(TextBox4.Text)  
ListBox1.AddItem FormatCurrency(price, 2)

但结果如下:

enter image description here

它应该是另一个(mew 1£3.50),而不是一个在另一个之上。

1 个答案:

答案 0 :(得分:3)

您需要指定列表框的列数和列宽,以防您希望它的行为类似于多列列表框。

试试这个

Option Explicit

Private Sub UserForm_Initialize()
    ListBox1.ColumnCount = 3
    ListBox1.ColumnWidths = "50;50"
End Sub

Private Sub CommandButton1_Click()
    With ListBox1
        .AddItem
        .List(.ListCount - 1, 0) = ComboBox1.Text  
        .List(.ListCount - 1, 1) = Val(TextBox4.Text) 
        .List(.ListCount - 1, 2) = FormatCurrency(price, 2)
    End With
End Sub

enter image description here

编辑:来自评论的跟进。

您不应该使用&的原因是,如果您有多行,则列中的数据将不会对齐。见这个例子

Private Sub CommandButton1_Click()
    With ListBox1
        .AddItem "Sid" & " " & "Rout" & " " & "Sample"
        .AddItem "Hello" & " " & "World" & " " & "Sample"
        .AddItem "Another" & " " & "Example" & " " & "Sample"
        .AddItem "Yet" & " " & "another" & " " & "Sample"
    End With
End Sub

这就是你将得到的

enter image description here

相关问题