15
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

在第二行,我收到一个错误,说需要对象。我试图将 g1val 和 g2val 设置为“Double”,并首先尝试将它们的值设为 1。但这些都没有成功。你能帮忙吗????

4

2 回答 2

12

为了设置整数变量的值,我们只需将值分配给它。例如g1val = 0,其中 as 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
于 2013-09-27T10:36:50.627 回答
10

Set 语句仅用于对象变量(如Excel或Excel 中) Range,而简单等号“=”用于基本数据类型,如. 您可以在此处找到有关何时使用 set的很好的解释。CellWorksheetInteger

另一个问题是,您的变量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,以防止程序中出现拼写错误。然后您必须声明所有变量,如果变量未知,编译器会给您一个警告。

于 2013-09-27T12:06:35.017 回答