使用函数在ms访问中搜索整行并返回列名

时间:2016-10-14 18:43:41

标签: vba function ms-access access-vba

可以使用一点帮助。以前我一直在使用IIF语句来获取此输出,但是IIF存在限制,现在正在寻找一个功能(在MS Access中)以满足要求。

挑战:需要在一行中搜索标准(例如标题00 \问题..),如果/当找到匹配时,它会使用带有查询的函数返回列名称(例如,FieldCategorization(Title 00 \ Question)点击下面的链接查看表格和所需的输出

Microsoft访问表:

Microsoft access table

查询所需的输出:

Desired output from query

我到目前为止搜索整个表格,它没有按行每行搜索:

Public Function FieldCategorization(TblName As String, Criteria As Long) As String
    Set dbs = CurrentDb
    Set rs = dbs.OpenRecordset(TblName)
    Dim fld As DAO.Field

    ' MyValue = 224803 ' T00 = Title 00\Question\First Name Text
    ' MyValue = 224814 ' AB00 = Abbreviation 00
    MyValue = Criteria

    'MsgBox "TblName: " & TblName & vbCrLf & "Criteria: " & Criteria

    rs.MoveFirst
    ' Move through each row in the recordset
    'Do While Not rs.EOF
        For Each fld In rs.Fields
            If fld = MyValue Then
                FieldCategorization = fld.Name
            End If
        Next fld
    rs.MoveNext
    'Loop

End Function

1 个答案:

答案 0 :(得分:0)

今天做了类似的事。下面的示例是超级简化的,但我认为它具有您正在寻找的所有元素。

    dim fld as fields
    dim rst, rstW as recordset

    MyValue = "Title 00\Question"

    Set dbs = currentdB
    Set rst = dbs.openrecordset ("table1")
    Set rstW = dbs.openrecordset  ("table2")

    rst.movefirst
    Do while not rst.eof
       for each fld in rst.fields
           if me(fld.name) = MyValue then
               rstW.addnew
               rstW!Title00 = fld.name
               rstW.update
           end if
       next fld
       rst.movenext
   Loop