[英]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.