|
本帖最后由 jany1312 于 2020-12-7 14:42 编辑
在学习VBA,基础不好,vba的算法和思路理解遇到的问题,求助老师帮讲解下。 代码中红色中文表达的疑问,即注释部分是我不懂的,完全不懂这套路
Sub 单元格笨循环()
Dim i&, j&, d&, s&, dPrice&, sPrice&, t
Dim source_area As Range, match_area As Range '源区域和匹配区域
t = Timer
Application.ScreenUpdating = False
Set source_area = [a1].CurrentRegion
Set match_area = [h1].CurrentRegion
For i = 2 To match_area.Rows.Count
d = -1 此处设置是什么意思,为何这样设置 d和s在这代码中实际代表了什么
s = -1 此处设置是什么意思,为何这样设置
For j = 2 To source_area.Rows.Count
If Cells(j, "b") = Cells(i, "i") And Cells(j, "c") = Cells(i, "j") Then
If d = -1 Then '<b>此处设置是什么意思,D就赋值一次为-1,为啥此处还判断是否为-1,根本不懂此处
d = Abs(Cells(i, "h") - Cells(j, "a")) '如果是第一次匹配就把数据赋值过来 为啥有好几处D 的赋值
dPrice = Cells(j, "d")
Else
'判断d 是不是最小
If d > Abs(Cells(i, "h") - Cells(j, "a")) Then 此处设置是什么意思,D就赋值一次为-1,为啥此处还判断,根本不懂此处
d = Abs(Cells(i, "h") - Cells(j, "a")) '简单的打擂台逻辑
dPrice = Cells(j, "d")
End If
End If
ElseIf d = -1 And Cells(j, "b") = Cells(i, "i") Then
If s = -1 Then
s = Abs(Cells(i, "h") - Cells(j, "a")) '如果是第一次匹配就把数据赋值过来
sPrice = Cells(j, "d")
Else
'判断s 是不是最小
If s > Abs(Cells(i, "h") - Cells(j, "a")) Then
s = Abs(Cells(i, "h") - Cells(j, "a")) '简单的打擂台逻辑
sPrice = Cells(j, "d")
End If
End If
End If
Next
If d <> -1 Then '如果内循环结束d 还是 -1 说明双条件都不匹配
Cells(i, "l") = dPrice
Else
Cells(i, "l") = sPrice
End If
Next
Application.ScreenUpdating = True
MsgBox "单元格循环嵌套运行时间:" & Timer - t
End Sub
|
|