我正在尝试使用组合框值创建一个简单的用户窗体,然后允许用户添加新项并保存这些项(在某种意义上,您将值键入文本框并同时更新了Combobox1
和Combobox2
和在关闭并重新打开excel文件后仍然保留)。这是我的代码:
Private Sub ComboBox1_Change()
End Sub
Private Sub ComboBox2_Change()
End Sub
Private Sub CommandButton1_Click()
Me.ComboBox2.AddItem Me.TextBox1.Value
Me.ComboBox1.AddItem Me.TextBox1.Value
Me.TextBox1.Value = ""
MsgBox "Category added to combobox!!"
End Sub
Private Sub UserForm_Activate()
Me.ComboBox1.AddItem "Chicken"
Dim sh As Worksheet
Dim i As Integer
End Sub
'更新列表并保存Excel文件
Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim strRowSource As String
Dim lReply As Long, lRows As Long
If ComboBox1 <> vbNullString Then
If ComboBox1.ListIndex < 0 Then
lReply = MsgBox(ComboBox1 & _
" is not part of the list. Add it", vbYesNo + vbQuestion)
If lReply = vbYes Then
With ComboBox1
strRowSource = .RowSource
lRows = Range(strRowSource).Rows.Count
Range(strRowSource).Cells(lRows + 1, 1) = ComboBox1
.RowSource = vbNullString
.RowSource = Range(strRowSource).Resize(lRows + 1, 1).Address
End With
End If
End If
End If
End Sub
建议
ComboBox1_Exit
事件。使用UserForm_QueryClose
事件。这样,您不必每次更改时都保存值。退出用户表单之前,请一口气进行操作。 逻辑
UserForm_Initialize
事件中,从工作表加载组合框。UserForm_QueryClose
事件中保存到工作表。确保先清除相关的列,然后再将值放回该列。样本代码
Option Explicit
Dim ws As Worksheet
Dim i As Long
'~~> Load values from the worksheet into the combobox
Private Sub UserForm_Initialize()
'~~> Set this to the relevant sheet
Set ws = Sheet1
Dim lRow As Long
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
ComboBox1.AddItem .Range("A" & i).Value
End If
Next i
End With
End Sub
'~~> Add item to combobox from textbox
Private Sub CommandButton1_Click()
If Len(Trim(TextBox1.Text)) <> 0 Then
ComboBox1.AddItem TextBox1.Text
Else
MsgBox "Nothing to add"
End If
End Sub
'~~> Save to worksheet
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ws.Columns(1).ClearContents
For i = 0 To ComboBox1.ListCount - 1
ws.Cells(i + 1, 1).Value = ComboBox1.List(i)
Next i
ThisWorkbook.Save
DoEvents
End Sub
Private Sub CommandButton1_Click()
If TextBox1.Text = "" Then Exit Sub
Dim myLastRow As Integer
myLastRow = Range("ItemList!A:A").SpecialCells(XlCellType.xlCellTypeLastCell).Row
'xlCellTypeLastCell is last cell that a range has data (not blank)
'but if any delete data here, will apply after save the worksheet
'For example if last is row 3 and col 1, and we delete row 2 and 3,
If myLastRow = 0 Then
ComboBox1.AddItem TextBox1.Text
Range("ItemList!A2").Value = TextBox1.Text
Exit Sub
End If
Dim myRange As Range
Set myRange = Range("ItemList!A2:A" & myLastRow).Find(TextBox1.Text)
If myRange Is Nothing Then
ComboBox1.AddItem TextBox1.Text
Range("ItemList!A" & myLastRow + 1).Value = TextBox1.Text
TextBox1.Text = ""
MsgBox "Category Added To ComboBox"
End If
End Sub
Private Sub UserForm_Activate()
ComboBox1.List = Range("ItemList!A2:A" & Range("ItemList!A:A").SpecialCells(XlCellType.xlCellTypeLastCell).Row).Value
End Sub