繁体   English   中英

从行、表、mdb 文件、excel/vba 中读取值?

[英]Reading a value, from a row, in a table, in an mdb file , from excel/vba?

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

现在我需要来自 excel/vba 的这个,稍后我将迁移到 vb.net

首先是我的数据库结构

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

它有一个名为“myParts”的表

该表有 3 列:id、部件号、部件描述

这是我想要制作的功能

函数 GetPartDescription (PartNumber as string) as string

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

所以这个函数应该,打开数据库,找到具有完全匹配零件号的行,然后返回该行的“零件描述”列中的任何内容

我该怎么做? 我试着通过选择哪个 api 来开始,我迷路了! DAO、ADO、ACEDAO、ADODB、ADO.NET、OLEDB ??? 什么样的恶梦 !

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

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

暂无
暂无

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

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