Private Sub CommandButton1_Click()
Dim rng As Range
Dim i As Range
Dim cell As Range
Dim Hvalue As Double
Dim Svalue As Double
Set rng = Selection
Hvalue = 0
Svalue = 0
For Each cell In rng
Next cell
If cell.Value > Hvalue Then Hvalue = cell.Value 'here i get run time error 91
For Each cell In rng
Next cell
If cell.Value < Hvalue And cell.Value > Svalue Then cell.Value = Svalue
MsgBox "hvalue= " & Hvalue & "svalue=" & Svalue
End Sub
答案 0 :(得分:1)
您的错误是因为变量cell
仅在循环内部本地有效,而您的if语句在循环之外。像这样在循环中移动if语句。
Private Sub CommandButton1_Click()
Dim rng As Range
Dim i As Range
Dim cell As Range
Dim Hvalue As Double
Dim Svalue As Double
Set rng = Selection
Hvalue = 0
Svalue = 0
For Each cell In rng
If cell.Value > Hvalue Then Hvalue = cell.Value
Next cell
For Each cell In rng
If cell.Value < Hvalue And cell.Value > Svalue Then cell.Value = Svalue
Next cell
MsgBox "hvalue= " & Hvalue & "svalue=" & Svalue
End Sub