我有一個用戶窗體,其中包含20個組合框,然後每個組合框旁邊有3個相應的文本框(所以共有60個文本框)。每個Combobox顯示相同的兩個選項(選擇1和選擇2)。與Combobox相鄰的3個文本框分別用於描述,項目數量和每個項目的價格。爲什麼For循環複製過程?
我已經使用For循環來循環20個Comboboxes。循環中的代碼將文本框中的輸入寫入表格格式的Excel工作表中。 Combobox的用途是將Excel中的表格中的文本框中的輸入分爲兩個選項(選項1和2)。
該代碼似乎適用於第一個Combobox,但是當我輸入第二個Combobox及其各自文本框的數據時,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
在此先感謝。
我是_guessing_這是因爲每次你通過'ComboBoxes'循環遍歷每個'TextBox'。你需要看看把兩者聯繫在一起。 – Bugs
的確,我也這麼認爲。我只是不知道該怎麼做 –
我提供了一些示例代碼,可以幫助您分組您的控件。我沒有深入瞭解代碼,但它可能會給你一個開始。當你有機會時讓我知道你的想法。 – Bugs