首页 > 解决方案 > 如何根据两个参数在表格中查找单元格(Excel)

问题描述

我有一张表,我需要根据使用的时间(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 

但是我如何循环遍历这些列?有没有更简单的方法将最终分数存储在变量中?

在此处输入图像描述

标签: excelvba

解决方案


请尝试下一个功能:

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变量作为参数的情况下发出警告,如果它们超出现有的范围限制等......


推荐阅读