[英]VBA loop through range of cells fails
出於某種原因,下面的代碼在第二行失敗,運行時錯誤“1004”說明“object '_Application' 的方法 'Intersect' 失敗”,並且在某些情況下我試圖修改它產生的代碼'_Global ' 失敗。 奇怪的是,我玩過這個代碼的各種版本,有時在調試模式下進行多次更改后,我重試了這個表單,然后它運行了。 如果我然后嘗試重新運行代碼,它會再次失敗。
rng1 是同一列中的一組單元格,rng2 是與 rng1 具有相同行的多列上的一組單元格
例如 rng1 = {A2:A10},rng2 = {D2:H10}
這些指令將 rng2 的單行中與 rng1 中的單個條目相關的單元格的值保存到數組中。 我檢查了這些范圍是否在同一張紙上,有效並且(在命名的地方)引用了正確的單元格。
For Each c In Range("rng1").Cells
For Each d In Application.Intersect(Rows(c.Row), Range("rng2")).Cells
*some instructions here*
Next d
Next c
試試這個,你的代碼對我造成錯誤的唯一一次是交叉點最終是空的。
Dim c As Range, d As Range
Dim rng As Range
For Each c In Range("test1")
Set rng = Application.Intersect(Rows(c.Row), Range("test2"))
If rng Is Nothing Then
'' Empty intersection ''
Debug.Print "Empty"
Else
For Each d In rng
'' some instructions here ''
Debug.Print d.Address
Next d
End If
Next c
當然,您可能還應該在表格前面加上Range
和Rows
,例如:
Sheet1.Rows
和
Sheet1.Range("test1")
等等……
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.