【发布时间】:2017-02-22 17:32:38
【问题描述】:
我有一个用户窗体,其中包含 20 个组合框,然后每个组合框旁边分别有 3 个文本框(总共 60 个文本框)。每个组合框都显示相同的两个选项(选项 1 和选项 2)。与组合框相邻的 3 个文本框分别用于描述、项目数量和每件价格。
我使用了一个 For 循环来循环 20 个 Combobox。循环中的代码将文本框中的输入以表格格式写入 Excel 工作表。组合框的目的是将文本框中的输入分成 Excel 工作表上的表格中的两个选项(选择 1 和 2)。
代码似乎适用于第一个组合框,但是当我为第二个组合框及其各自的文本框输入数据时,Excel 工作表上的数据被复制了几次,我不知道为什么。
这是代码:
Dim i as Integer 'row counter
Dim j As Integer
Dim h As Integer
Dim ctrl As Control
Dim num As Integer
Dim txt As Control
For Each ctrl In Me.custom_prices.Controls
If TypeName(ctrl) = "ComboBox" Then
If ctrl = "Choice 1" Then
j = i
For Each txt In Me.custom_prices.Controls
If TypeName(txt) = "TextBox" And txt.Tag = "DESCRIPTION" Then
For num = 1 To 20
If txt.Value = "" Then Exit For
If Controls("textbox" & num).Value = "" Then Exit For
If Controls("textboxprice" & num).Value = "" Then Exit For
If Controls("textboxno" & num).Value = "" Then Exit For
ActiveCell.Offset(rowOffset:=j, columnOffset:=0).Value = Controls("textbox" & num).Value
ActiveCell.Offset(rowOffset:=j, columnOffset:=1).Value = Controls("textboxprice" & num).Value
ActiveCell.Offset(rowOffset:=j, columnOffset:=2).Value = Controls("textboxno" & num).Value
ActiveCell.Offset(rowOffset:=j, columnOffset:=3).Value = Controls("textboxno" & num).Value * Controls("textboxprice" & num).Value
j = j + 1
sub_total = sub_total + (Controls("textboxno" & num).Value * Controls("textboxprice" & num).Value)
Next num
End If
Next txt
i = j
sub_total_3 = sub_total
sub_total = 0
ElseIf ctrl = "Choice 2" Then
h = i
For Each txt In Me.custom_prices.Controls
If TypeName(txt) = "TextBox" And txt.Tag = "DESCRIPTION" Then
For num = 1 To 20
If txt.Value = "" Then Exit For
If Controls("textbox" & num).Value = "" Then Exit For
If Controls("textboxprice" & num).Value = "" Then Exit For
If Controls("textboxno" & num).Value = "" Then Exit For
ActiveCell.Offset(rowOffset:=h, columnOffset:=0).Value = Controls("textbox" & num).Value
ActiveCell.Offset(rowOffset:=h, columnOffset:=1).Value = Controls("textboxprice" & num).Value
ActiveCell.Offset(rowOffset:=h, columnOffset:=2).Value = Controls("textboxno" & num).Value
ActiveCell.Offset(rowOffset:=h, columnOffset:=3).Value = Controls("textboxno" & num).Value * Controls("textboxprice" & num).Value
h = h + 1
sub_total = sub_total + (Controls("textboxno" & num).Value * Controls("textboxprice" & num).Value)
Next num
End If
Next txt
i = h
sub_total_4 = sub_total
sub_total = 0
Else: ctrl = ""
sub_total = sub_total
End If
End If
Next ctrl
提前致谢。
【问题讨论】:
-
我猜测这是因为每次您循环访问
ComboBoxes时,您都会循环访问每个TextBox。您需要考虑以某种方式将两者联系在一起。 -
没错,我也这么认为。我只是不知道该怎么做
-
我提供了一些示例代码,可以帮助您对控件进行分组。我没有深入研究代码,但它可能会给你一个开始。如果有机会,请告诉我您的想法。