srt*_*srt 12 excel vba excel-vba
Dim g1val, g2val As Integer
Set g1val = 0
Set g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
Run Code Online (Sandbox Code Playgroud)
在第二行我得到一个错误,说明对象是必需的.我试图使g1val和g2val为"Double",并试图首先给它们的值为1.但那些没有成功.你可以帮忙?? ....
San*_*osh 11
为了设置整数变量的值,我们只需为其赋值.例如g1val = 0
,使用set关键字将值赋给对象.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
Run Code Online (Sandbox Code Playgroud)
该Set语句仅用于对象变量(如Range
,Cell
或Worksheet
在Excel中),而简单的等号 "="用于基本数据类型一样Integer
.你可以在这里找到何时使用set的好解释.
另一个问题是,您的变量g1val
实际上并未声明为Integer
,但具有类型Variant
.这是因为Dim语句不能按照您期望的方式工作,这里(参见下面的示例).变量必须立即跟随其类型,否则其类型将默认为Variant
.你只能这样缩短你的Dim语句:
Dim intColumn As Integer, intRow As Integer 'This creates two integers
Run Code Online (Sandbox Code Playgroud)
因此,您将在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
Run Code Online (Sandbox Code Playgroud)
您的代码还有两个注意事项:
第一句话: 而不是写作
'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
Run Code Online (Sandbox Code Playgroud)
你可以简单地写
'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
Run Code Online (Sandbox Code Playgroud)
因为你不想g1val
在其他情况下改变.
第二句话:我鼓励你在编程时使用Option Explicit,以防止程序中的拼写错误.然后,您必须声明所有变量,如果变量未知,编译器将给出警告.