Set 语句仅用于对象变量(如Excel或Excel 中) Range
,而简单等号“=”用于基本数据类型,如. 您可以在此处找到有关何时使用 set的很好的解释。Cell
Worksheet
Integer
另一个问题是,您的变量g1val
实际上并未声明为Integer
,而是类型为Variant
。这是因为Dim 语句没有按照您期望的方式工作,这里(参见下面的示例)。变量必须紧跟其类型,否则其类型将默认为Variant
. 您只能通过这种方式缩短 Dim 语句:
Dim intColumn As Integer, intRow As Integer 'This creates two integers
因此,您将在 Watches 窗口中看到“Empty”而不是预期的“0”。
试试这个例子来理解区别:
Sub Dimming()
Dim thisBecomesVariant, thisIsAnInteger As Integer
Dim integerOne As Integer, integerTwo As Integer
MsgBox TypeName(thisBecomesVariant) 'Will display "Empty"
MsgBox TypeName(thisIsAnInteger ) 'Will display "Integer"
MsgBox TypeName(integerOne ) 'Will display "Integer"
MsgBox TypeName(integerTwo ) 'Will display "Integer"
'By assigning an Integer value to a Variant it becomes Integer, too
thisBecomesVariant = 0
MsgBox TypeName(thisBecomesVariant) 'Will display "Integer"
End Sub
关于您的代码的另外两个通知:
第一句话:
而不是写
'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
g1val = g1val 'Don't change g1val
Else
g1val = Cells(33, i).Value 'Otherwise set g1val to the cell's value
End If
你可以简单地写
'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
g1val = Cells(33, i).Value 'Set g1val to the cell's value
End If
因为你不想g1val
在另一种情况下改变。
第二点:我鼓励您在编程时使用Option Explicit,以防止程序中出现拼写错误。然后您必须声明所有变量,如果变量未知,编译器会给您一个警告。