Excel VBA-如果单元格未填充颜色,则将数据验证放在单元格中

Excel VBA-如果单元格未填充颜色,则将数据验证放在单元格中,excel,vba,validation,Excel,Vba,Validation,我正在尝试向没有填充颜色的单元格添加数据验证。对于我尝试过的代码(见下文),出于某种原因,它仍然会将数据验证添加到范围内的每个单元格,即使它们填充了颜色 感谢您的帮助 Sub Data_Validation() Dim WS As Worksheet Dim WS2 As Worksheet Dim Range1 As Range, Range2 As Range Dim c As Range Set WS = ThisWorkbook.Worksheets("Report") Set WS

我正在尝试向没有填充颜色的单元格添加数据验证。对于我尝试过的代码(见下文),出于某种原因,它仍然会将数据验证添加到范围内的每个单元格,即使它们填充了颜色

感谢您的帮助

Sub Data_Validation()

Dim WS As Worksheet
Dim WS2 As Worksheet
Dim Range1 As Range, Range2 As Range
Dim c As Range

Set WS = ThisWorkbook.Worksheets("Report")
Set WS2 = ThisWorkbook.Worksheets("List")

'these are two cells in column A, but they may change position if rows are added, so I named them. 
Set Range1 = WS.Range("DV_Start:DV_End") 

'This is the named range for cells on the List worksheet:
Set Range2 = WS2.Range("ListCells")

For Each c In Range1

    If c.Interior.ColorIndex <> xlNone Then

    Else

        With Range1.Validation
            .Delete
            .Add Type:=xlValidateList, _
                Formula1:="='" & WS2.Name & "'!" & Range2.Address
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = "Name"
            .ErrorTitle = "ERROR: Invalid"
            .InputMessage = "Please enter or select something..."
            .ErrorMessage = "What you have entered is invalid. Please try again."
            .ShowInput = True
            .ShowError = True
        End With

    End If

Next

End Sub
子数据_验证()
将WS设置为工作表
将WS2设置为工作表
变光范围1作为范围,范围2作为范围
调光范围
设置WS=ThisWorkbook.Worksheets(“报告”)
Set WS2=ThisWorkbook.Worksheets(“列表”)
'这是列A中的两个单元格,但如果添加行,它们的位置可能会改变,因此我将它们命名为。
设置范围1=WS.Range(“DV\u开始:DV\u结束”)
'这是列表工作表上单元格的命名范围:
设置Range2=WS2.Range(“列表单元格”)
对于范围1中的每个c
如果c.Interior.ColorIndex xlNone,则
其他的
范围1.验证
.删除
.Add类型:=xlValidateList_
公式1:=“='”&WS2.Name&“!”&Range2.Address
.IgnoreBlank=True
.InCellDropdown=True
.InputTitle=“名称”
.ErrorTitle=“错误:无效”
.InputMessage=“请输入或选择某个内容…”
.ErrorMessage=“您输入的内容无效。请重试。”
.ShowInput=True
.ror=真
以
如果结束
下一个
端接头

根据吉佩德的评论:

c.interior.colorindex
更改为
c.interior.pattern
,并将
范围验证更改为
c.Validation


让它工作起来。再次感谢吉佩德

如果是c.Interior.PATTERN xlNone,则
带有c.Validation
Hi Jeeped!这就解决了!!非常感谢:)我们能把这归因于打字错误吗?还是你更愿意在下面给出正式的回答?@mitchmitch24你也可以去掉
Else
,只需将你的
If
If Not c.Interior.ColorIndex xl None然后