从当前数据库的表中选择一个值并在 Access VBA 中使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3754489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:06:12  来源:igfitidea点击:

Select a value from a table in current DB and use a variable in Access VBA

ms-accessvba

提问by MaxTag

In Access VBA, I want to use values from a "Settings" table, instead of hard-coding folder locations etc. in the code. I can't figure out how to load a value from the table and use it in the code.

在 Access VBA 中,我想使用“设置”表中的值,而不是代码中的硬编码文件夹位置等。我不知道如何从表中加载一个值并在代码中使用它。

Dim oFSystem As Object
Dim oFolder As Object
Dim oFile As Object
Dim sFolderPath As String



sFolderPath = "C:\Documents and Settings\Main\Desktop\Files" 'BAD BAD, I WANT TO AVOID THIS

I have created a table "Settings", and I want to use the value

我创建了一个表“设置”,我想使用该值

SELECT TOP 1 Settings.SettingsValue FROM Settings WHERE (((Settings.SettingName)="Files Folder Location"));

采纳答案by KevenDenen

One way:

单程:

Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim sFolderPath As String

Set db = CurrentDb()
Set rs1 = db.OpenRecordset("SELECT TOP 1 SettingsValue FROM Settings WHERE SettingName="Files Folder Location")

If rs1.RecordCount > 0 Then
    rs1.MoveFirst
    sFolderPath = rs1.Fields("SettingsValue")
End If
rs1.Close
set rs1 = Nothing
set db = Nothing

回答by HansUp

You could use the DLookup function if you have only one record where SettingName="Files Folder Location".

如果您只有一条记录,其中 SettingName="Files Folder Location",则可以使用 DLookup 函数。

sFolderPath = DLookup("SettingsValue", "Settings", "SettingName=""Files Folder Location""")