2014-03-27 68 views
0

我目前正在使用VBA在Excel中將一個Sudoku程序作爲項目工作,我需要將一個單元格範圍存儲在一個變量中。如何在一個變量中存儲一系列單元格

沿東西這行:

''' 
dim grid as string 

grid = range("b3:j11") 
''' 

但我不知道該怎麼調暗格的。 我試過整數,字符串和範圍,但網格似乎永遠不會有價值。 我還假設我沒有正確指定範圍到變量

///////////////////////////// ////

下面的回覆im粘貼代碼在這裏。 duplicatecheck函數通過一系列單元格來檢查它們是否超過某個數字,然後相應地突出顯示單元格

正如我想查看不同範圍的單元格以進行不同的檢查,我需要可變所以該函數可以

然而當可變網格被稱爲在它沒有價值的duplicatecheck功能和theirfor沒有細胞被檢查

Dim row As Integer 

Dim col As Integer 

Dim grid As Variant 

Dim checkmark As Integer 


Sub Rowcheck() 

    checkmark = 1 
    row = 0 
    col = 0 

    grid = range("b3:j3").Value 

    For row = 0 To 8 

     duplicatecheck 

    Next row 

結束子

重複使用的範圍
Function duplicatecheck() 

Dim safe As Boolean 

Dim check As Integer 

Dim x As Integer 

     ' check each number in a range for duplicates starting with 1 
For check = 1 To 9 
    If Application.Worksheet.Function.CountIf(Selection.Offset(row, col), range(grid)).check = 1  Then 
' if number is only found once 
safe = True 
    ElseIf Application.Worksheet.Function.CountIf(Selection.Offset(row, col), range(grid)).check < 1 Then 
' if the number is found less than once in the range 
safe = False 
    ElseIf Application.Worksheet.Function.CountIf(Selection.Offset(row, col), range(grid)).check > 1 Then 
' if the number is found more than once 
Selection.Offset(row, x).range(grid).Interior.colour = vbBlue ' highlight the range red 

     If checkmark = 1 Then 
       For x = 0 To 8 
        Selection.Offset(row, x).range(geid).Value = check 
        Selection.Offset(row, x).range.ont.colour = vbRed 
       Next x 
     ElseIf checkmark = 2 Then 
       For x = 0 To 8 
        Selection.Offset(x, col).range(grid).Value = check 
        Selection.Offset(x, col).range.ont.colour = vbRed 

       Next x 
       safe = False 
       error = True 

    If safe = False Then 
     complete = False 
    End If 

結束如果 結束如果 接着檢查 端功能

+0

我試過這個代碼和Rons但都沒有工作。 將網格設置爲範圍或變量後,在網格或設置網格=範圍(「b3:j11」)後,變量網格仍然沒有值時稍後調用 – user2920648

+0

檢查我對Ron的回答的評論。變體可以存儲範圍或值。如果您嘗試存儲值,請使用範圍的值,而不是範圍本身。 – Manhattan

回答

2

儲存於一個變型

Dim vGrid as Variant 
vGrid = range("B3:J11") 

vGrid隨後將是基於1-2D陣列,與暗淡1 =行和DIM2 =列

例如B3的內容將是vGrid(1,1)

編輯:看來你現在使用Grid作爲Range對象的字符串參數,並且存在CountIF問題。

設置選項明確和需要變量聲明的選項,如我在評論中提到的。

至於你COUNTIF聲明,如果你正在檢查的範圍是,在電網中聲明,你的標準是在Selection.Offset(行,列),則該行應該是這個樣子:

If Application.WorksheetFunction.CountIf(Range(grid),Selection.Offset(Row, col)) = 1 Then ... 

請注意,我已更正您的使用函數作爲工作表對象的屬性;將範圍和標準參數按正確的順序排列;並刪除了在該函數結尾添加的.check。

+0

我設置了網格作爲變體並運行代碼'grid = range(「b3:j11」)',但是當稍後調用變量網格時,它仍然沒有值 – user2920648

+1

使用'vGrid = Range(「B3 :J11「)。價值'而不是。這應該存儲範圍的*值*而不是範圍本身。 *在一個變量中存儲一個範圍*和*存儲一個範圍的值/ s *存在巨大差異。 – Manhattan

+0

@ user2920648如果填充該範圍的工作表不是ActiveSheet,則需要指定工作表。如果這不起作用,請發佈更多代碼 –

相關問題