《excel 2007实用资料,VBA+图表+bible宝典+word 2007宝典》
通常可以去掉重复项和空单元格后再设置数据有效性,但如果不想改变单元格的结构,可以使用下面的VBA代码来解决这个问题,假如要设置下拉列表的单元格为D5,数据区域为K8:K38,步骤如下:
1.按Alt+F11,打开VBA编辑器。
2.在“工程”窗口中双击要包含数据有效性设置的工作表,在右侧代码窗口中输入下列代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim RowNum, ListRows, ListStartRow, ListColumn As Integer
Dim TheList As String
Dim Repeated As Boolean
If Target.Address <> "$D$5" Then Exit Sub
With Range("k8:K38")
ListRows = .Rows.Count
ListStartRow = .Row
ListColumn = .Column
End With
For RowNum = 0 To ListRows - 1
Repeated = False
If Not IsEmpty(Cells(ListStartRow + RowNum, ListColumn)) Then
For i = 0 To RowNum - 1
If Cells(ListStartRow + RowNum, ListColumn) = Cells(ListStartRow + i, ListColumn) Then
Repeated = True
Exit For
End If
Next i
If Not Repeated Then TheList = TheList & Cells(ListStartRow + RowNum, ListColumn) & ","
End If
Next RowNum
TheList = Left(TheList, Len(TheList) - 1)
With Range("D5").Validation
.Delete
.Add _
Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=TheList
End With
End Sub
3.关闭VBA编辑器返回Excel界面,选择D5单元格,单击下拉箭头即可看到不包含空值和无重复的下拉列表。
说明:上述代码使用了工作表的SelectionChange事件,当在工作表中重新选择单元格后会执行上述代码。需根据实际将代码中的单元格“D5”和区域“k8:K38”进行更改。 |