从excel / vba中,从表中的行中读取值,在mdb文件中?

时间:2018-08-29 08:46:20

标签: excel-vba access-vba ado

我想做一个简单的函数,它将打开并从数据库(和mdb文件)读取。尽可能简单和干净。最好只使用ADODB。

现在我需要excel / vba的支持,以后我将迁移到vb.net

首先是我的数据库结构

单个mdb文件(实际上是accdb,我希望这没关系)

它有一个名为“ myParts”的表

此表有3列:id,零件号,零件描述

这是我要制作的功能

函数GetPartDescription(PartNumber作为字符串)作为字符串

零件号在整个表格中只能存在一次。

因此,此函数应打开数据库,找到具有完全匹配的部件号的行,然后返回该行的“部件描述”列中的所有内容

我应该怎么做?我试图通过选择哪种api来上手,我迷路了! DAO,ADO,ACEDOO,ADODB,ADO.NET,OLEDB ???真是一场噩梦!

1 个答案:

答案 0 :(得分:1)

IMO这个问题应该解决得太广泛,但让我们尝试一下 以下功能将通过ADODbD连接到Access数据库

Function ConnectToDB(ByVal fileName As String)

Dim conn As New ADODB.Connection

    If Dir(fileName) = "" Then
        MsgBox "Could not find file " & fileName
        Exit Function
    End If

    Dim connectionString As String

    ' https://www.connectionstrings.com/access/
    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" _
                       & fileName & ";Persist Security Info=False;"

    conn.Open connectionString

    Set ConnectToDB = conn

End Function

这可能会给您您想要的。您需要使用代号为shRepAllRecords的工作表才能使其正常工作。

Option Explicit

Sub ReadFromDB()

    ' Get datbase name
    Dim dbName As String
    dbName = <fule filename of the database>

    ' Connect to the databse
    Dim conn As ADODB.Connection
    Set conn = ConnectToDB(dbName)

    ' read the data
    Dim rs As New ADODB.Recordset
    Dim query As String

    ' First example to use an SQL statement
   query = "SELECT * From myParts WHERE PartNumber = '123'"

    ' Second example to use a query name defined in the database itself
    ' query = "qryCustomer"

    rs.Open query, conn

    ' shRepAllRecords is the codename of the sheet where the 
    ' data is written to

    ' Write header
    Dim i As Long
    For i = 0 To rs.Fields.Count - 1
        'shRepAllRecords.Cells(1, i + 1).Value = rs.Fields(i).Name
        shRepAllRecords.Range("A1").Offset(0, i) = rs.Fields(i).Name
    Next i

    ' Write Data
    shRepAllRecords.Range("A2").CopyFromRecordset rs
    shRepAllRecords.Activate


    ' clean up
    conn.Close

End Sub

您需要调整代码以完全获得所需的内容,但我将其留给您。

相关问题