2014-01-15 67 views
0

我有一個組合框填充值。我想在組合框中選擇一個值,然後單擊「添加」按鈕將此值放入下面的某些單元格中。我可以使用下面的代碼將一個項目添加到我的列表中,但我希望能夠添加多個項目。我覺得我非常接近,我只需要一些調整!如何在單元格中選擇從組合框創建列表並使用VBA選擇按鈕?

Private Sub CommandButtonAddItem_Click() 

Dim ws As Worksheet 
Dim box As ComboBox 
Dim food As String 
Dim num As Integer 
num = 19 


Set ws = Worksheets("sheet1") 
Set box = ws.OLEObjects("ComboBox1").Object 

food = box.Value 
Worksheets("sheet1").Cells(num, 1) = food 

If Worksheets("sheet1").Cells(num, 1) = " " Then 
Worksheets("sheet1").Cells(num, 1) = food 

num = num + 1 
End If 


End Sub 

回答

0

嘗試這個!

如果「默認」單元格已被佔用,它將繼續向下直到它找到一個不是空的,然後將該值放入該單元格中。

Private Sub CommandButtonAddItem_Click() 

Dim ws As Worksheet 
Dim box As ComboBox 
Dim food As String 
Dim num As Integer 
num = 19 


Set ws = Worksheets("sheet1") 
Set box = ws.OLEObjects("ComboBox1").Object 

food = box.Value 

While Worksheets("sheet1").Cells(num, 1) <> "" 

    num = num + 1 

Wend 

Worksheets("sheet1").Cells(num, 1) = food 

End If 

End Sub 
+0

這似乎更接近!我認爲一段時間的陳述會更合適,但我無法找到一種方法來實現它。請幫助我多一點!編譯器在「num = num + 1」行處出現「溢出」錯誤。我從來沒有見過這個錯誤,它可以修復,還是有更多的調試? – user3199958

+0

這意味着'num'溢出了'int'的最大值。 –

+0

嘗試將num從'Integer'更改爲'Long'或'Variant' –

相關問題