打开访问表格以访问从Excel工作表单元格中选择的特定记录

时间:2019-07-05 01:25:14

标签: excel vba ms-access

我正在处理我要负责的工作问题。在excel工作表中,有一个ID列表和一个MS Access数据库,其中包含与这些记录对应的记录。我需要编写代码来打开从excel字段标识的记录的访问表单。

Sub OpenAccess()

   Dim LPath As String
   Dim StudentID As Integer

   'Path to Access database
   LPath = "C:\Users\Admin\Desktop\CNRC_Test.accdb"

   'Open Access and make visible
   Set oApp = CreateObject("Access.Application")
   oApp.Visible = True

   'Open Access database as defined by LPath variable
   oApp.OpenCurrentDatabase LPath

   'Open form called Categories filtering by CategoryID

   oApp.DoCmd.OpenForm "Student Details", , , "Student ID=" & StudentID


End Sub

我尝试了以下代码:

Sub OpenAccess()

   Dim LPath As String
   Dim StudentID As Integer

   'Path to Access database
   LPath = "C:\Users\Admin\Desktop\CNRC_Test.accdb"

   'Open Access and make visible
   Set oApp = CreateObject("Access.Application")
   oApp.Visible = True

   'Open Access database as defined by LPath variable
   oApp.OpenCurrentDatabase LPath

   'Open form called Categories filtering by CategoryID

   oApp.DoCmd.OpenForm "Student Details", , , "Student ID=" & StudentID


End Sub

2 个答案:

答案 0 :(得分:1)

  

oApp.DoCmd.OpenForm“学生详细信息”,“,”学生ID =“&学生ID

在Office 16上进行测试:如果“学生详细信息”是表单的名称,并且表单的“记录源”是您要从中获取的表,而“学生ID”是索引号列,则有一个表单上带有“控件源”的文本字段,该控件源是该索引号列或表中其他列的名称,那么应该返回一条记录(结果在文本框中)。

一个例子如下:

首先,将您的函数def改写为OpenAccess(StudentID)

接下来,从您要使用的工作表中分配StudentID:

用您选择的索引值填充B3。

然后将活动单元暂时停在A1中。

然后从左VBE窗格的VBAProject树中的Microsoft Excel对象中弹出Sheet对象。将此写入其模块:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 If Target.Address = "$B$3" Then
  Call OpenAccess(Target.Value)
 End If
End Sub

然后单击进入B3。

答案 1 :(得分:0)

您可以将此代码复制/粘贴到Excel工作表模块的后面,并根据需要对其进行自定义:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim studentID As Long

    ' Exit if selection is more than one cell
    If Target.Cells.Count > 1 Then
        Exit Sub
    End If

    ' Validate if selected cell is in range
    If Not Application.Intersect(Range("A1:A5"), Range(Target.Address)) _
           Is Nothing Then

        ' Assign studentid value from current cell
        studentID = Target.Value

        ' Call the open procedure with current cell value
        Call OpenAccess(studentID)

    End If

End Sub


Sub OpenAccess(studentID As Long)


    Dim oApp As Object
    Dim LPath As String


    'Path to Access database
    LPath = "C:\Temp\Test.accdb"

    ' Check if Access is open
    On Error Resume Next
        Set oApp = GetObject(LPath)
        If Err.Number <> 0 Then Err.Clear
    On Error GoTo 0

    oApp.Visible = True

    'Open form called Categories filtering by CategoryID
    oApp.DoCmd.OpenForm "Student Details", , , "[Student ID]=" & studentID


End Sub