0

const在 VBA 模块中有一些,但我想将它们放在 INI 文件中,因为我有其他使用相同常量的应用程序。这有效:

Public Const PATH_DB As String = "\\server\folder\bdd.mdb"

然而这不起作用:

Public Const PATH_DB As String = getFromIni("path","db","C:\config.ini")

Public Function getFromIni(ByVal strSectionName As String, ByVal strEntry As String, ByVal strIniPath As String) As String
    Dim x As Long
    Dim sSection As String, sEntry As String, sDefault As String
    Dim sRetBuf As String, iLenBuf As Integer, sFileName As String
    Dim sValue As String

    sSection = strSectionName
    sEntry = strEntry
    sDefault = ""
    sRetBuf = Strings.String$(256, 0) '256 null characters
    iLenBuf = Len(sRetBuf$)
    sFileName = strIniPath
    x = GetPrivateProfileString(sSection, sEntry, "", sRetBuf, iLenBuf, sFileName)
    sValue = Strings.Trim(Strings.Left$(sRetBuf, x))

    If sValue <> "" Then
        getFromIni = sValue
    Else
        getFromIni = vbNullChar
    End If
End Function
# C:\config.ini
[path]
db=\\server\folder\bdd.mdb

我的 getFromIni 函数实际上工作得很好,但当我想声明常量时却不行(它根本不编译)。我尝试了一个全局变量,但由于某种原因,它也不起作用,从同一个项目中的另一个表单使用时找不到该变量(它仅在它被声明为 const 时才有效,但我不能声明它从函数中获取值时作为 const)。

怎么了?

4

2 回答 2

3

您不能将函数调用分配为 CONST 字符串的值。我希望您在运行此程序时收到错误“需要常量表达式”。

于 2012-10-05T13:54:02.170 回答
1

改变

Public Const PATH_DB As String = getFromIni("path","db","C:\config.ini")

Public PATH_DB As String 

将以下从 INI 文件中获取值的调用放在初始化方法中(比如数据库打开事件)

PATH_DB = getFromIni("path","db","C:\config.ini")
于 2012-10-05T13:53:25.417 回答