【问题标题】:Excel VBA Validation List to Comma Separated List in CellExcel VBA验证列表到单元格中的逗号分隔列表
【发布时间】:2017-10-07 02:42:09
【问题描述】:

我正在尝试创建 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”而中断:对象“_Global”的方法“范围”失败。

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

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

【问题讨论】:

  • 问题不在于范围,而在于某些单元格没有验证并且没有错误处理以避免停止运行所有内容

标签: vba excel


【解决方案1】:

您可以使用 Intersect 和 SpecialCells 仅循环通过具有验证的单元格。 On Error 行是为了避免在没有此类单元格时出现错误消息(这可能是您的原因)。

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

【讨论】:

  • 谢谢!这很好用。我也尝试添加错误处理,这绝对是个问题。