Excel VBA验证列表到单元格中逗号分隔的列表

Excel VBA验证列表到单元格中逗号分隔的列表,vba,excel,Vba,Excel,我正在尝试创建VBA代码,以便在工作表(最终是工作簿)中运行,并为每个具有验证的单元格生成逗号分隔的列表。我能够使用以下代码在定义的范围内实现我的目标: Sub ValidationPrintOut2() Dim cell As Range Dim oldstr As String Dim newstr As String Dim usedcell As Range For Each usedcell In ActiveSheet.Range("N1

我正在尝试创建VBA代码,以便在工作表(最终是工作簿)中运行,并为每个具有验证的单元格生成逗号分隔的列表。我能够使用以下代码在定义的范围内实现我的目标:

Sub ValidationPrintOut2()

    Dim cell As Range
    Dim oldstr As String
    Dim newstr As String

    Dim usedcell As Range

    For Each usedcell In ActiveSheet.Range("N1:N3")
        For Each cell In Range(usedcell.Validation.Formula1)
            oldstr = ActiveSheet.Cells(usedcell.Row, usedcell.Column + 2)
            newstr = cell.Value

            ActiveSheet.Cells(usedcell.Row, usedcell.Column + 2) = oldstr + ", " + newstr
        Next cell
    Next usedcell
End Sub
但是,当我试图将代码扩展到列(下面)中的已使用范围时,代码以方法错误“1004”结束:对象“\u Global”的方法“range”失败

Sub ValidationPrintOut2()

    Dim cell As Range
    Dim oldstr As String
    Dim newstr As String

    Dim usedcell As Range

    For Each usedcell In ActiveSheet.UsedRange.Columns("N")
        For Each cell In Range(usedcell.Validation.Formula1)
            oldstr = ActiveSheet.Cells(usedcell.Row, usedcell.Column + 2)
            newstr = cell.Value

            ActiveSheet.Cells(usedcell.Row, usedcell.Column + 2) = oldstr + ", " + newstr
        Next cell
    Next usedcell
End Sub

有人能解释一下为什么会发生这种情况以及如何解决这个问题吗?谢谢

您可以使用Intersect和SPECIALCELL仅在单元格中循环进行验证。“On Error line”是为了避免在没有此类单元格的情况下出现错误消息(这可能是导致您出现错误的原因)


问题不在于范围,而在于某些单元格没有验证,并且没有错误处理来避免停止运行。谢谢!这很有效。我也尝试过添加错误处理,这绝对是个问题。
Sub ValidationPrintOut2()

Dim cell As Range
Dim oldstr As String
Dim newstr As String

Dim usedcell As Range

On Error Resume Next
For Each usedcell In Intersect(ActiveSheet.UsedRange, Columns("N").SpecialCells(xlCellTypeAllValidation))
    For Each cell In Range(usedcell.Validation.Formula1)
        oldstr = ActiveSheet.Cells(usedcell.Row, usedcell.Column + 2)
        newstr = cell.Value
        ActiveSheet.Cells(usedcell.Row, usedcell.Column + 2) = oldstr + ", " + newstr
    Next cell
Next usedcell

End Sub