2016-01-09 60 views
0

我在A1中放置了一个下拉菜单作为“汽车”和“自行车”,一旦我选择“汽车”或“自行车”,它应显示sheet5中各个品牌的汽车和自行车列表。从下拉列表中选择应显示结果

从下拉列表中选择“汽车”或“自行车”后,我必须运行一个宏。

但是,一旦我从下拉菜单中选择任何一个,结果应该显示而不是运行宏模块。

下面我用模块

Sub validation() 

    Dim MyList(2) As String 
    MyList(0) = "Cars" 
    MyList(1) = "Bikes" 
    MyList(2) = "" 

    With Range("A1").validation 
     .Delete 
     .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ 
      Operator:=xlBetween, Formula1:=Join(MyList, ",") 
    End With 

    If Range("A1") = "Cars" 
     Sheets("Sheet5").Range("Carsbrand").Copy Destination:=Sheets("Sheet1").Range("B9:E17") 
     'the above line copies car brand names from sheet5 
    ElseIf Range("A1") = "Bikes" Then 
     Sheets("Sheet5").Range("Bikesbrand").Copy Destination:=Sheets("Sheet1").Range("B9:E11") 
     'the above line copies car brand names from sheet5 
    End If 
End Sub 

回答

0

你的代码设置数据验证细胞A1,但它实际上并没有放任何东西A1,因此既列表复制。

你需要另一个,事件宏,监视更改单元格A1 进行复制。将这个在表代码区

Private Sub Worksheet_Change(ByVal Target As Range) 
    Dim A1 As Range 
    Set A1 = Range("A1") 
    If Intersect(A1, Target) Is Nothing Then Exit Sub 

    Application.EnableEvents = False 
     If Range("A1") = "Cars" Then 
      Sheets("Sheet5").Range("Carsbrand").Copy Destination:=Sheets("Sheet1").Range("B9:E17") 
     ElseIf Range("A1") = "Bikes" Then 
      Sheets("Sheet5").Range("Bikesbrand").Copy Destination:=Sheets("Sheet1").Range("B9:E11") 
     End If 
    Application.EnableEvents = True 
End Sub 

编辑#1:

这个版本将避免警告消息,并试图粘贴之前清理目标区域:

Private Sub Worksheet_Change(ByVal Target As Range) 
    Dim A1 As Range 
    Set A1 = Range("A1") 
    If Intersect(A1, Target) Is Nothing Then Exit Sub 

    Application.EnableEvents = False 
     Sheets("Sheet1").Range("B9:E17").Clear 
     If Range("A1") = "Cars" Then 
      Sheets("Sheet5").Range("Carsbrand").Copy Destination:=Sheets("Sheet1").Range("B9:E17") 
     ElseIf Range("A1") = "Bikes" Then 
      Sheets("Sheet5").Range("Bikesbrand").Copy Destination:=Sheets("Sheet1").Range("B9:E11") 
     End If 
    Application.EnableEvents = True 
End Sub 
+0

感谢您的更正,但是由于汽车数据为10个单元,自行车数据为8个单元,因此如果选择了自行车,则最后2个汽车单元保持相同。因此,我在下面的“行(”9: 10“)。EntireRow.Hidden = True”如下。但是如果我们选择其他下拉菜单,它会问你是否要替换现有数据 如果Range(“A1”)=“Bike”Then Row(“8:10”)。EntireRow.Hidden = False –

+0

@SrinivasMantri容易避免Excel的警告....我会**编辑**我的回答 –

+0

@SrinivasMantri请参阅我的**编辑#1。** –

-2

如果我正确地理解了你,你希望宏在单元格A1中的选项被选中后立即运行自己?

+0

是的,这是我的要求 –