2017-05-08 101 views
0

列表中我正在制作费用表单,但我正在努力查看费用类别列表,我想使其能够输入我选择的类别一个输入框,然后进入一个用作数据验证的列表。 我希望这些值加入到A列在Sheet2上Excel VBA - 将数值从输入框添加到列表

我已经试过以下至今

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 

回答

1

提供已经有验证的范围内,你可以做这样的事情(未测试):

编辑:

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 
+0

我已经试过这一点,它显示“运行 - 时间错误'1004': 应用程序定义或对象定义的错误@Jordan –

+0

哪条线产生该错误? – Jordan

+0

'strList = .Formula1' –