我的代码运行得很好,但是每次都要运行两次代码才能得到正确的答案,谁能告诉我为什么会这样?bug出现在for循环中的某个地方,注解为“找到static.press单元格位置”
Sub find()
Dim A As Double
Dim B As Variant
Dim c As Integer
Dim x As Range
Dim cell As Range
Dim rng As Variant
Dim r As Variant
Dim Mx As Long
Dim i As Long
Dim target As Double
Set wks = Worksheets("comefri")
Set wkks = Worksheets("TEST")
Dim p As Long
'RPM INPUT
A = wkks.Range("C18").value
'Static Pressure Input
B = wkks.Range("C19").value
'copy comefri values to test sheet
Sheets("comefri").Range("A9:gs24").Copy Destination:=Sheets("test").Range("a1:gs16")
With test
' Row Numb used in rangelookup
c = Range("C20").value
d = Range(Cells(c, 102), Cells(c, 201))
For Each cell In [a2:gs16]
cell = WorksheetFunction.Round(cell, 1)
Next cell
'Finds RPM cell location
Set cell = Range("a:a").find(What:=A, LookAt:=xlWhole, MatchCase:=fasle, SearchFormat:=False)
Range("c20") = cell.row
'finds static.press cell location
target = B
Set rng = Range(Cells(c, 102), Cells(c, 201))
'rng.Offset(, 1).ClearContents
Mx = Application.Max(rng)
For Each B In rng
If Abs(target - B) < Mx Then
Mx = Abs(target - B)
i = B.row
p = B.Column
End If
Next B
Debug.Print i
Debug.Print p
Range("d19").value = p
Range("e19").value = i
End With
End Sub
第一次运行代码时,我认为它使用的是以前输入的值,第二次运行时,它使用的是新的输入。
1条答案
按热度按时间ulmd4ohb1#
问题是您从储存格值(
Sheets("TEST").Range("C20")
)中提取c
的值。您更新储存格值(在此行:Range("c20") = cell.row
),但不要更新c
的值。因此,当您设置rng
变量时,它仍然使用旧的c
值。要解决此问题,请使用以下方法:
使用此选项:
最后一些一般性建议: