问题描述
我有一张桌子,需要根据使用的时间(A和B列)和得分(第2行)找到最终得分。例如如果该人使用43秒并获得11分,则最终得分将为10。
我的第一个想法是在时间中反复循环以获得这样的行号:
Do Until (.Range("A" & i).Value <= time) And _
(.Range("B" & i).Value >= time)
i = i + 1
Loop
cellN = i
然后遍历各个点以获取列字母,然后将它们与以下内容添加在一起:
finalScore = .Range(cellL & cellN).Value
但是如何遍历各列?有没有更简单的方法将最终分数存储在变量中?
解决方法
请尝试下一个功能,
Function FinalScore(lTime As Long,points As Long) As Long
Dim sh As Worksheet,lastRow As Long,lastCol As Long
Dim colP As Long,i As Long
Set sh = ActiveSheet 'use here your specific worksheet
lastRow = sh.Range("A" & Rows.count).End(xlUp).Row
lastCol = sh.cells(1,Columns.count).End(xlToLeft).Column
For i = 2 To lastRow
If lTime >= sh.Range("A" & i).Value And _
lTime <= sh.Range("B" & i).Value Then
colP = WorksheetFunction.Match(points,sh.Rows(2),0)
FinalScore = sh.cells(i,colP).Value: Exit Function
End If
Next i
End Function
可以通过以下方式调用/检查它:
Sub testFinalScore()
MsgBox FinalScore(43,11)
End Sub
这是基本的。必须通过一些错误处理部分加以改进。在未使用Long
变量作为参数的情况下发出警告,如果它们超过了现有范围限制等...