A for each
循環通過集合。你有一個稱爲查詢行的範圍。你有一個名爲c的範圍。你所做的是循環查詢行中的每個範圍...這意味着c將只是查詢行。
你想
for each c in queryrow.cells
此外,要知道這是關於儘可能低效率的,因爲它是通過所有65000個左右列將循環,而不是隻是相對較少,實際上有數據。
編輯:我不知道爲什麼這仍然讓你錯誤。你還有其他的邏輯錯誤。這種執行對我來說(它也是善良的愛,縮進!),如果我在一些資料扔從B2:H21,例如:
Sub test()
Dim worksheetname As Worksheet
Set worksheetname = ActiveWorkbook.ActiveSheet
Dim queryaddress As Range
Dim notoffsetnum As Integer
Dim anotherarrayofnumbers() As Integer
Dim c As Range
For Each queryaddress In worksheetname.Range("B2:B21")
Dim queryrow As Range
Set queryrow = queryaddress.EntireRow
notoffsetnum = 0
For Each c In queryrow.Cells
If c.Interior.Color <> 192 And Not IsEmpty(c.Value) Then
notoffsetnum = notoffsetnum + 1
ReDim Preserve anotherarrayofnumbers(notoffsetnum)
anotherarrayofnumbers(notoffsetnum - 1) = c.Value
End If
Next c
Next queryaddress
Dim i As Integer
For i = 0 To UBound(anotherarrayofnumbers) - 1
Debug.Print anotherarrayofnumbers(i)
Next i
End Sub
,這是很容易解決的另外一個問題是,是默認,VBA陣列是基於0的。他們從0開始,而你錯誤地從1開始.VBA不會拋出錯誤,它只會有元素0爲0.
你真正的問題是,在每行之後,你敲出舊的數組因爲notoffsetnum會回到0,然後你將數組重新回到1的大小。這會拋棄所有內容,最後你會得到最後一行。我假設這是一個錯誤。由於這是一個很大的問題,我認爲這個東西有點乾淨,不那麼脆弱。我所做的唯一假設是,你從B2開始,並且你有數據向下和向右。如果這將是一個問題,你可以改變一下。我想你會發現range.end(xl ...)方法是一個救星。如果你按下ctrl +箭頭鍵,它將把你獲得的單元格作爲你的單元格,因此它是查找範圍邊緣的一種快速方法。
Sub BetterSolution()
Dim ws As Worksheet
Set ws = ActiveWorkbook.ActiveSheet
Dim firstCell As Range
Set firstCell = ws.Range("B2")
Dim lastCol As Integer
lastCol = firstCell.End(xlToRight).Column
Dim lastRow As Integer
lastRow = firstCell.End(xlDown).Row
Dim lastCell As Range
Set lastCell = ws.Cells(lastRow, lastCol)
Dim arr() As Integer
Dim rng As Range
Dim index As Integer
index = 0
For Each rng In ws.Range(firstCell, lastCell).Cells
index = index + 1
ReDim Preserve arr(index + 1)
arr(index) = rng.Value
Next rng
End Sub
做循環的所有非空單元格實際上是否包含整數值?當發生錯誤時,使用立即窗口檢查notoffsetnum的值,然後查看相應單元格中的值 – barrowc
@barrowc這是問題所在,我沒有爲'c.Value'之一設置整數值。過濾這個值會終止錯誤。 –