VBA GetPrivateProfileString

VBA GetPrivateProfileString

我想用 GetPrivateProfileString 读取 INI 文件。
问题是我的字符串包含一些不应该出现的字符

我认为这个问题来自 path = String(255,0) 但如果我不写这个,我的 Excel 程序就会停止工作。

有没有办法绕过这个问题或者我的代码有问题?

Dim path as String,m2_path as string
path = String(255, 0)
m2_path = String(255, 0)

nc = GetPrivateProfileString("PATH", "path1", "", path, 255, inipath)
nc = GetPrivateProfileString("PATH", "path2", "", m2_path, 255, inipath)

函数

Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" _
             (ByVal lpApplicationName As String, _
               ByVal lpKeyName As String, _
               ByVal lpDefault As String, _
               ByVal lpReturnedString As String, _
               ByVal nSize As Long, _
               ByVal lpFileName As String) As Long

INI 文件

[PATH]
path1="G:\Arbeit\gen molding"
...

值 nc 告诉您字符串中有多少个字符。问题是实际接口是字符数组:不是字符串。所以你要做的就是最好地猜测你可能得到多少个字符(nsize),它会告诉你有多少个字符。

dim path1 as string, path2 as string, path as string

path = string(255, 0)
nc = GetPrivateProfileString("PATH", "path1", "", path, 255, inipath)
path1 = left(path, nc)
nc = GetPrivateProfileString("PATH", "path2", "", m2_path, 255, inipath)
path2 = left(path, nc)