用Vba代码写一个程序,运行后实现在sheet1表格中,如果a列内容为水果,那b列出现香蕉、苹果、雪梨、火龙果下拉多选框;如果a列内容为蔬菜,则b列出现白菜、菠菜、西兰花、包菜下拉多选框,若选择两个以上,用分号隔开。
时间: 2023-05-20 18:03:54 浏览: 102
OfficeVBA宏使用宏实现表格中根据一列分类拆分到对应的sheet表中
以下是实现该功能的 VBA 代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Fruit() As String
Dim Vegetable() As String
Dim i As Integer
Fruit = Split("香蕉,苹果,雪梨,火龙果", ",")
Vegetable = Split("白菜,菠菜,西兰花,包菜", ",")
If Target.Column = 1 Then
If Target.Value = "水果" Then
With Target.Offset(0, 1).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:=Join(Fruit, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
ElseIf Target.Value = "蔬菜" Then
With Target.Offset(0, 1).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:=Join(Vegetable, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Else
Target.Offset(0, 1).ClearContents
End If
End If
If Target.Column = 2 Then
If Target.Value <> "" Then
Target.Value = Replace(Target.Value, ", ", ";")
End If
End If
End Sub
当 A 列的单元格的值为“水果”时,B 列的单元格会出现香蕉、苹果、雪梨、火龙果下拉多选框;当 A 列的单元格的值为“蔬菜”时,B 列的单元格会出现白菜、菠菜、西兰花、包菜下拉多选框。如果选择两个以上,用分号隔开。
阅读全文