繁体   English   中英

如何在excel VBA中根据行和列ID查找单元格值

[英]How to find cell value based on row and Column ID in excel VBA

需要一个 VBA Sub 来根据行和列 ID 查找单元格值。 在下面的示例中,我需要选择 East 和 RT3 相交的值,即 80。

A   B   C   D   E
1   null    RT1 RT2 RT3 RT4
2   North   31  40  78  11
3   South   32  41  79  12
4   East    33  42  80  13
5   West    34  43  81  14

使用类似于以下未测试

Function getcell(ct as string, rt as string) as range

    With activecell
        R = .columns("A").find(rt).row
        C = .rows("1").find(ct).Column
        'The below will escape the function if none where found
        If r = nothing or c = nothing then exit function
        Set getcell = .cells(r, c)
    End with

End function

有不同的方法可以做到这一点,但一种方法是使用带参数的函数。 你没有说你打算如何传递参数,所以我只是用一个子来调用函数。

Function GetValue(row As Integer, col As Integer)
    GetValue = ActiveSheet.Cells(row, col)
End Function

Sub CallGetValue()
    Dim cellval As String
    cellval = GetValue(row:=4, col:=4)
    MsgBox (cellval)
End Sub

我知道我迟到了,但也许对未来的人来说。 我想出了这个:

它需要一个 ListObject 表,它会在其中找到有趣的单元格并返回它的字符串。

当 a) 未找到表名,b) 行或 c) 未找到列名时返回 ERROR(这取决于您如何编辑)

大约需要:0.0005s (5E-04s)

Public Function GetTableVal(ByVal tblName As String, ByVal rowName As String, ByVal colName As String) As String

    On Error Resume Next
        Dim rng As Range
        Set rng = Range(tblName)
    On Error GoTo 0
    
    If rng Is Nothing Then
        GetTableVal = "ERROR: Table not found"
        Exit Function
    End If
    
    Dim tbl As ListObject
    Set tbl = rng.ListObject
     
    On Error Resume Next
        Dim colIndex As Long
        colIndex = tbl.ListColumns(colName).INDEX
    On Error GoTo 0
        
    If colIndex = 0 Then
        GetTableVal = "ERROR: Column not found"
        Exit Function
    End If
    
    Dim rowIndexRange As Range
    Set rowIndexRange = tbl.ListColumns(1).Range.Find(rowName, LookIn:=xlValues, LookAt:=xlWhole)
    
    If rowIndexRange Is Nothing Then
        GetTableVal = "ERROR: Row not found"
        Exit Function
    End If
    
    Dim rowIndex As Long
    rowIndex = rowIndexRange.row - tbl.Range.row + 1
    
    Dim res As Range
    Set res = tbl.Range(rowIndex, colIndex)
     
    GetTableVal = res.value

End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM