2017-05-08 102 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' –