使用vba根据所选菜单自动填充excel上的特定列

我试图根据Excel中第一列的选定下拉选项自动填充下一列。

在这里输入图像说明

下面我想到的初始代码示例,但似乎我的做法是不正确的。

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 

可能是你在这之后:

 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”?)代码窗格中,而不是在正常的模块代码窗格中

我不认为你需要worksheet_change()函数

用名为cbTest的combobox我会这样做

 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