将VBA转换为VBS

时间:2012-11-30 14:04:55

标签: vba ms-access vbscript converter

我有一些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?谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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