您需要将水平单元格中的值存储在字符串中,然后将其用于数据验证。
假设:
假设您的数据如下所示,并且您想A1:M13
在单元格中显示列表D4
代码:
Sub Sample()
Dim ws As Worksheet
Dim aCell As Range, rng As Range
Dim sList As String
'~~> Set this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> This is the range which has the horz list
Set rng = .Range("A1:M1")
'~~> Get the values of each cell and store it in a string
For Each aCell In rng
sList = sList & "," & aCell.Value
Next
sList = Mid(sList, 2)
'~~> Adding the data validation to say Cell D4
With .Range("D4").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=sList
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
输出:
当你运行上面的代码,你会看到结果