2017-03-16 39 views
1

我想根據Excel中第一列的選定下拉選項自動填充下一列。根據所選菜單使用vba自動填充excel上的特定列

enter image description here

下面,我認爲最初的代碼樣本,但似乎我的做法是不正確。

Private Sub WorksheetStore_Change(ByVal Target As Range) 
    Dim i As Integer 
    Dim intCol As Integer 

    intCol = shtStoreGroup.Range("A") 
    If Not IsEmpty(Target.value) And intCol > 1 And Target.Columns.Count = 1 And Target.Column = intCol And Target.Row > Start_Row Then 
     For i = Target.Row To Target.Row + Target.Rows.Count - 1 
      If shtStoreGroup.Columns(intCol).Rows(i).value = "Create" Then 
       shtStoreGroup.Columns(intCol + 2).Rows(i).value = "N/A" 
       shtStoreGroup.Columns(intCol + 3).Rows(i).value = "Test" 
     Next i 
    End If 
End Sub 
+0

我想「WorksheetStore」是您的工作表的名稱。但是當你的組合框值發生變化時,你應該做些事情。例如:'Private Sub comboBoxName_Change()... End Sub' – tretom

+0

或者當它失去焦點時:'Private Sub comboBoxName_LostFocus()... End Sub' – tretom

+0

您可能想要添加更多關於涉及多少張表的細節,名稱,應該開始發生什麼,應該在哪裏觸發,... – user3598756

回答

1

可能是你在這之後:

Private Sub Worksheet_Change(ByVal target As Range) 

    If Not ValidateTarget(target, 2) Then Exit Sub '<-- exit if function validating 'Target' returns 'False' 

    On Error GoTo EXITSUB ' <-- be sure to handle possible errors properly 
    Application.EnableEvents = False '<--| disable events handling not to run this sub on top of itself 
    Select Case UCase(target.Value) 
     Case "CREATE" 
      target.Offset(, 2).Value = "N/A" 
      target.Offset(, 3).Value = "Test" 
     Case "DELETE" 
      target.Offset(, 2).Value = "???" 
      target.Offset(, 3).Value = "Test??" 
    End Select 

EXITSUB: 
    Application.EnableEvents = True '<--| restore events handling 
End Sub 

Function ValidateTarget(target As Range, Start_Row As Long) As Boolean 
    With target 
     If .columns.Count > 1 Then Exit Function 
     If .Column <> 1 Then Exit Function 
     If .Row <= Start_Row Then Exit Function 
     If IsEmpty(.Value) Then Exit Function 
     ValidateTarget = True 
    End With 
End Function 

發生在相關工作表(?「shtStoreGroup」)代碼窗格上面的代碼,而不是在一個正常的模塊代碼窗格

+0

感謝這一個工作 – Dren

0

我不認爲你需要worksheet_change()函數

與命名cbTest組合框我不喜歡它

Option Explicit 
Sub fill() 

    cbTest.AddItem ("Value1") 
    cbTest.AddItem ("Value2") 

End Sub 

Private Sub cbTest_Change() 
    Select Case cbTest.Value 
    Case "Value1" 
     Cells(1, 1).Value = "Test" 
    Case "Value2" 
     Cells(1, 2).Value = "Test2" 
    End Select 
End Sub