2017-03-16 273 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