【发布时间】: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
有人能解释一下为什么会发生这种情况以及如何解决这个问题吗?谢谢!
【问题讨论】:
-
问题不在于范围,而在于某些单元格没有验证并且没有错误处理以避免停止运行所有内容