Excel VBA – 将input框中的值添加到列中的列表中

我目前正在制作费用表格,但是我正在努力寻找费用类别清单,我想这样做是为了让我可以在input框中键入我select的类别,然后进入一个用作数据validation。 我想要将值添加到Sheet2的列A.

到目前为止,我已经尝试过了

Sub Button1_Click() Dim ExpenseName As String ExpenseName = InputBox( _ "Type in the name of the category you want to add", _ "Add Expense Category", _ "Type expense category here") If Len(ExpenseName) = 0 Then MsgBox "No category chosen" Exit Sub End If '**Struggling what to put here** End Sub 

我已经添加了下面,请参阅。

 Sub Button1_Click() Dim ExpenseName As String ExpenseName = InputBox( _ "Type in the name of the category you want to add", _ "Add Expense Category", _ "Type expense category here") If Len(ExpenseName) = 0 Then MsgBox "No category chosen" Exit Sub End If Dim strList As String Dim ws As Worksheet Dim eRow As Long eRow = Sheet2.Cells(Sheet2.Rows.Count, 1).End(xlUp).Row With ThisWorkbook.Sheets("Sheet1").Range("D4:D21").Validation .Delete 'Delete previous validation .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Formula1:="=Sheet2!$A$1:$A$" & eRow End With End Sub 

如果已经在范围内进行了validation,则可以这样做(未testing):

编辑:

 Sub Button1_Click() Dim ExpenseName As String Dim eRow as Long ExpenseName = InputBox( _ "Type in the name of the category you want to add", _ "Add Expense Category", _ "Type expense category here") If Len(ExpenseName) = 0 Then MsgBox "No category chosen" Exit Sub End If With ThisWorkbook.Sheets("Sheet2") eRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 .Cells(eRow, "A").Value = ExpenseName End With With ThisWorkbook.Sheets("Sheet1").Range("D4:D21").Validation .Delete 'Delete previous validation .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Formula1:= "=Sheet2!$A$1:$A$" & eRow End With End Sub