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

ここで 2 行目に、オブジェクトが必要であるというエラーが表示されます。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 など) にのみ使用され、単純Range等号'=' は のような基本データ型に使用されます。set hereをいつ使用するかについての良い説明を見つけることができます。CellWorksheetInteger

もう 1 つの問題は、変数g1valが実際には として宣言されていないIntegerが、型が であることVariantです。これは、Dim ステートメントが期待どおりに機能しないためです (以下の例を参照)。変数の直後にその型が続く必要があります。そうでない場合、その型はデフォルトで になりますVariant。Dim ステートメントは次の方法でのみ短縮できます。

Dim intColumn As Integer, intRow As Integer  'This creates two integers

このため、[Watches] ウィンドウには、予想される "0" ではなく "Empty" が表示されます。

違いを理解するには、次の例を試してください。

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

コードに関するさらに 2 つの通知:

最初の発言: 書く代わりに

'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他のケースでは変更したくないので。

2 つ目の注意点:プログラムのタイプミスを防ぐために、プログラミング時にはOption Explicitを使用することをお勧めします。次に、すべての変数を宣言する必要があり、変数が不明な場合、コンパイラは警告を出します。

于 2013-09-27T12:06:35.017 に答える