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在这里的第二行,我收到一个错误,说object required.I,我试图将g1val和g2val设置为“双精度”,并试图为它们在first.But中的值给1,但没有成功。你能帮上忙吗??...
发布于 2013-09-27 18:36:51
为了设置整型变量的值,我们只需给它赋值。例如g1val = 0,其中as set关键字用于为object赋值。
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发布于 2013-09-27 20:06:35
Excel语句仅用于对象变量(如中的Range、Cell或Worksheet ),而简单的等号 '=‘用于Integer等基本数据类型。你可以为when to use set here找到一个很好的解释。
另一个问题是,您的变量g1val实际上并没有声明为Integer,而是具有类型Variant。这是因为在这里,Dim语句的工作方式与您预期的不同(参见下面的示例)。变量后面必须紧跟其类型,否则其类型将默认为Variant。你只能这样缩短你的Dim语句:
Dim intColumn As Integer, intRow As Integer 'This creates two integers因此,您将在“监视”窗口中看到“空”而不是预期的"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,以防止程序中的打字错误。然后你必须声明所有的变量,如果一个变量未知,编译器会给你一个警告。
https://stackoverflow.com/questions/19048601
复制相似问题