任意のフォームの特定レコードに移動

Public Sub prcMoveFocusToRecord(ByVal strFormName As String, ByVal strFieldName As String, ByVal varSearchValue As Variant)
    Dim frmTarget As Form           ' 対象フォーム
    Dim rstClone As DAO.Recordset   ' クローンレコードセット
    Dim strCriteria As String       ' 検索条件

    ' フォームオブジェクトを取得
    Set frmTarget = Forms(strFormName)

    ' 検索条件を構築
    Select Case VarType(varSearchValue)
        Case vbString
            strCriteria = "[" & strFieldName & "] = '" & varSearchValue & "'" ' 文字列型
        Case vbDate
            strCriteria = "[" & strFieldName & "] = #" & Format(varSearchValue, "yyyy/mm/dd") & "#" ' 日付型
        Case Else
            strCriteria = "[" & strFieldName & "] = " & varSearchValue ' 数値型
    End Select

    ' クローンレコードセットを取得し検索
    Set rstClone = frmTarget.RecordsetClone
    rstClone.FindFirst strCriteria

    ' レコード移動
    frmTarget.Bookmark = rstClone.Bookmark

    ' オブジェクト解放
    rstClone.Close
    Set rstClone = Nothing
    Set frmTarget = Nothing
End Sub

コメント