2017-10-06 72 views
1

我試圖創建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: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 

有人可以解釋爲什麼會發生這種情況,以及如何解決這個問題?謝謝!

+0

問題不在此範圍,但事實上,一些細胞沒有確認,也沒有錯誤處理,以避免運行 –

回答

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 
+1

感謝停止了一切!這很好。我玩過增加錯誤處理,這絕對是問題。 – bark16

相關問題