我正在处理一些VBA代码,而且我正在使用
参数不是可选的
错误。我查看了这个问题的其他一些答案,他们似乎没有回答我的问题。
代码在Sub Finding_number ()
的第一次迭代时卡住了,这让我感到困惑。我没有向该Sub传递任何参数,为什么会出错呢?
我的代码:
Sub Pedal_Actuations_per_hour()
Dim counter As Integer
Dim average_actuations As Single
counter = 1
Do While IsEmpty(ActiveCell.Value) = False
Finding_number
average_actuations = (average_actuations + Pedal_actuations()) / counter
counter = counter + 1
Loop
Range("J2").Value = average_actuations
End Sub
Sub Finding_number()
Dim index As Integer
index = 1
Range("E2").Select
Do While index = 1
If ActiveCell.Value = 121 Then
index = 0
End If
Range.Offset (1)
Loop
End Sub
Function Pedal_actuations() As Integer
Dim time_sum As Single
Dim index As Integer
index = 1
time_sum = 0
Do While time_sum < 1
If IsEmpty(ActiveCell.Value) = 0 Then
date_number = Int(ActiveCell(, -2).Value)
ActiveCell(, 6).Value = ActiveCell(, -2).Value - date_number
ActiveCell(, 7).Value = Abs(ActiveCell(, 6).Value - ActiveCell(2, 6)) *24
Else
index = 0
End If
Pedal_actuations = Pedal_actuations + 1
time_sum = time_sum + ActiveCell(, 7).Value
Loop
End Function
答案 0 :(得分:2)
可能
Range.Offset (1)
您可能希望将代码更改为
Sub Finding_number()
Dim index As Integer
index = 1
Dim rng As Range
Set rng = Range("E2")
Do While index = 1
If rng.Value = 121 Then index = 0
Set rng = rng.Offset(1, 0)
Loop
End Sub
那么,出了什么问题?
您希望使用之前在代码中选择的Range,然后转到下一个Cell,依此类推。
你可能想做的是
Selection.Offset(1, 0).Select
这会将当前所选单元格下的单元格偏移,然后选择它。
但是:更好的做法是使用
定义和设置范围对象Dim rng As Range
Set rng = Range("E2")
然后使用
将其设置为每个循环后的下一个单元格Set rng = rng.Offset(1, 0)
最后,为了进一步改进您的潜艇,请考虑您是否真的需要index
- 变量。这是没有它的镜头
Sub Finding_number()
Dim rng As Range
Set rng = Range("E2")
Do While Not rng.Value = 121
Set rng = rng.Offset(1, 0)
Loop
End Sub
答案 1 :(得分:2)
最好避免使用Select
,ActiveCell
等等...
而是将引用的对象用作Sheets
和Range
s。
Sub Finding_number()
Dim index As Integer
index = 1
Dim Rng As Range
Set Rng = Range("E2")
Do While index = 1
If Rng.Value = 121 Then
index = 0
End If
Set Rng = Rng.Offset(1)
Loop
End Sub
下面的较短版本会给你相同的结果:
Sub Finding_number()
Dim Rng As Range
Set Rng = Range("E2")
Do While Rng.Value <> 121
Set Rng = Rng.Offset(1)
Loop
End Sub