1

我有一个小 VBA 脚本,其中包含一些我想转换为单个 VBS 文件的功能。

这是我得到的一个例子:

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

Private Function ReadIniFileString(ByVal Sect As String, ByVal Keyname As String) As String
    Dim Worked As Long
    Dim RetStr As String * 128
    Dim StrSize As Long
    Dim iNoOfCharInIni As Integer
    Dim sIniString, sProfileString As String

    iNoOfCharInIni = 0
    sIniString = ""
    If Sect = "" Or Keyname = "" Then
        MsgBox "Erreur lors de la lecture des paramètres dans " & IniFileName, vbExclamation, "INI"
        Access.Application.Quit
    Else
        sProfileString = ""
        RetStr = Space(128)
        StrSize = Len(RetStr)
        Worked = GetPrivateProfileString(Sect, Keyname, "", RetStr, StrSize, IniFileName)
        If Worked Then
            iNoOfCharInIni = Worked
            sIniString = Left$(RetStr, Worked)
        End If
    End If
    ReadIniFileString = sIniString
End Function

然后,我需要使用此函数将一些值放入字符串中。VBS 似乎不喜欢我的任何 var 声明 ( (Dim) MyVar As MyType)。

如果我能够使该代码适应 VBS,我也应该能够完成我的其余功能。如何将其调整/转换为 VBS?谢谢你。

4

2 回答 2

2

遗憾的是,我之前没有看到这一点,无论如何,为了将来的参考,这里是一个纯 vbscript 解决方案,用于从 ini 文件中读取值。如果有人需要对使用的正则表达式进行解释,请发表评论。

'this is the contents of test.ini'
' [Brussels]
' Address = "Postbox 3245_58348 Brussels"

' [Copenhagen]
' Address = "Postbox 2455_5478347 Copenhagen"

' [Paris]
' Address = "Postbox 8546_5412557 Paris"

section = "Brussels"
key = "Address"

const ForReading = 1
set fso = CreateObject("Scripting.FileSystemObject")
set file = fso.OpenTextFile("test.ini", ForReading)

'returns "Postbox 3245_58348 Brussels"'
wscript.echo get_key_of_ini(file.readall, section, key)

function get_key_of_ini(readFile, section, key)
  set regEx = New RegExp
  with regEx
    .Pattern = "(\[" & section & "\]\r\n)([^\[]+)"
    .IgnoreCase = True 
    .Global = True
  end With

  set matches  = regEx.execute(readFile)
  for x = 0 to matches.count-1
    set match = matches(x)
    For i = 1 To match.subMatches.count-1
      subMatches = match.SubMatches(i)
      if trim(split(match.SubMatches(i),"=")(0)) = key then
        get_key_of_ini = trim(split(match.SubMatches(i),"=")(1))
      end if
    Next
  next
end function
于 2012-11-30T17:02:36.333 回答
1

由于您有一个 MDB 可以执行您想要的操作,因此运行 VBS 脚本以打开此 mdb 并设置 AutoExec 宏以运行压缩这些数据库的函数,然后自行关闭 MDB。这有点hacky,但可能被证明是最不麻烦的。

于 2012-11-30T15:22:07.590 回答