2017-04-11 37 views
1

我一直在嘗試創建一個程序來自動解決在Excel中使用VBA作爲項目的數獨遊戲。ReDim在循環過程中導致運行時錯誤9

我遇到了一個問題,在我的數組沒有得到分配給它們的正確值後,通過一個循環來拾取它們。我已經爲3x3矩陣進行了這種設計工作,但它在9x3x3(IE完全數獨謎題)方面存在問題。

我檢查了ReDim文檔並意識到它只能重新分配數組的最後一個維度。正因爲如此,我試圖去處理邏輯,所以它永遠不需要改變前兩個維度的大小。我仍然遇到一個錯誤,當試圖從數組中調用一個值時,我被認爲超出了數組的範圍。我已經使用調試器一步一步地完成了程序,並檢查它是否正確地分配了所有值。我對自己爲什麼不能正常工作感到無能爲力,因此有沒有人可以給我的建議?

Dim guessArray() As integer 
Dim blockArray() As Integer 
Dim blockCheckArray() As integer 
Dim correctArray() As Integer 
Dim lenBlockArray (3, 3, 1) As Integer 
Dim lenBlockCheck(3, 3, 1) As integer 
Dim lenBlockCheckArray (3, 3, 1) As integer 
Dim counter as integer 

'Putting the sudoku into an array 


ReDim guessArray (9, 9) As integer 

For i = 1 to 9 

    For j = 1 to 9 

     guessArray (i, j) = Cells (i, j) 

    Next 

Next 

'Creating an array to find the numbers that are in a quadrant 

ReDim blockCheckArray(3, 3, 1) As integer 

For a = 1 to 3 

    For b = 1 to 3 

     For i = 1 to 3 

      For j = 1 to 3 

       'Looking through each quadrant for any number != 0 and dumping them into an array 

       If guessArray (i + ((a - 1) * 3), j + ((b - 1) * 3)) <> 0 Then 

        lenBlockArray (a, b, 1) = lenBlockArray (a, b, 1) + 1 

        ReDim Preserve blockArray (3, 3, lenBlockArray (a, b, 1)) As Integer 

        blockArray (a, b, lenBlockArray (a, b, 1)) = guessArray (i + ((a - 1) * 3), j + ((b - 1) * 3)) 

        End If 

      Next 

     Next 

    Next 

Next 

'Writing out the numbers in the quadrants for debugging 

counter = 1 

For a = 1 to 3 

    For b = 1 to 3 

     For i = 1 to lenBlockArray (a, b, 1) 

      Cells (counter, i + 10) = blockArray (a, b, i) 

     Next 

    Next 

Next 

我使用Excel 2010中這是我在計算器上的第一篇文章,它從我的手機是(我在我的停機時間做這個項目的工作),所以如果有任何改變格式或任何細節關於我收到的錯誤,請隨時提問。

+0

缺少'lenBlockArray()'函數。請發佈,以便提供幫助的人可以瀏覽您的代碼。 –

+0

@AdamVincent排序,謝謝。在移動設備上發佈信息的危險。 – Hutsan

回答

1

你的問題是,你是基於什麼的lenBlockArray(a, b, 1)當前值復位的blockArray的第三維 - 但數組中的各種數值可能會有所不同 - 所以,如果lenBlockArray(1,1,1)爲3,因此blockArray的尺寸是(3,3,3) ,那麼當您將lenBlockArray(1,2,1)設置爲1時,您將重新調整blockArray(3,3,1)

您應該將blockArray改爲UBound(blockArray,3)lenBlockArray(a,b,1)中較大的一個。

If UBound(blockArray, 3) < lenBlockArray(a, b, 1) Then 
    ReDim Preserve blockArray (3, 3, lenBlockArray (a, b, 1)) As Integer 
End If 
+0

感謝您的支持!我不知道它是如何不點擊的,我將blockArray重置爲每次迭代1或2次。非常感激。 – Hutsan