[英]How do I store a range of cells in a variable
我目前正在使用VBA作為Excel中的一個項目來開發Sudoku程序,我需要將一個單元格區域存儲在一個變量中。
與此類似:
'''
dim grid as string
grid = range("b3:j11")
'''
但是我不確定如何將網格變暗。 我試過整數,字符串和范圍,但網格似乎從來沒有值。 我還假設我沒有將范圍正確分配給變量
/////////////////////////////////
按照我將代碼粘貼到此處的答復。 復制檢查功能會檢查一系列單元格,以檢查它們是否超過某個特定數目,然后相應地突出顯示單元格
因為我想查看不同范圍的單元格以進行不同的檢查,所以我需要將該范圍設為變量,以便可以重用該功能
但是,當在duplicatecheck函數中調用變量網格時,它沒有任何值,並且沒有對它們的單元格進行檢查
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
如果結束則結束如果下一步檢查結束功能
將其存儲在變體中
Dim vGrid as Variant
vGrid = range("B3:J11")
然后,vGrid將是基於2D 1的數組,其中Dim 1 =行,Dim2 =列
例如B3的內容將在vGrid(1,1)中
編輯:看來您現在正在使用Grid作為Range對象的字符串參數,並且CountIF有問題。
如我在注釋中所述,設置Option Explicit和要求變量聲明的選項。
就您的CountIF語句而言,如果要檢查的范圍是在Grid中聲明的范圍,而您的條件在Selection.Offset(row,col)中,則該行應類似於:
If Application.WorksheetFunction.CountIf(Range(grid),Selection.Offset(Row, col)) = 1 Then ...
請注意,我已更正了您將Function用作Worksheet對象的屬性的問題; 將范圍和條件參數按適當順序排列; 並刪除了在該函數末尾添加的.check。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.