温馨提示:本文翻译自stackoverflow.com,查看原文请点击:forms - Parse enum values by name in VBA
forms powershell vba

forms - 在VBA中按名称解析枚举值

发布于 2020-04-07 10:34:44

我想编写一些VBA代码,该代码应将MSForms常数名称(作为字符串,例如“ fmTextAlignLeft”给出)解析为其实际值。由于没有本机的方法,因此我正在考虑将常量的名称放入Powershell代码中,然后将执行该代码并返回结果。

Private Sub ParseEnumByName(EnumConst As String)
    Dim WScript As New WshShell
    Dim PSCode As String
    Dim Result
    PSCode = "(some code)" & EnumConst & "(more code with exit $Value statement)"

    Result = WScript.Run("Powershell -command """ & PSCode & """", 0, True)

    ParseEnumByName = Result
End Sub

通过遍历MSForms库中的所有枚举并使用类似于[System.Enum]::GetNames( [System.Windows.Forms.FormBorderStyle] )或也许类似于以下说明的方法从它们中获取值,这应该是可行的 如何将字符串转换为枚举?

问题在于System.Windows.Forms库包含的枚举和类型名与VBA中可用的MSForms库完全不同。

我尝试Add-Type -Path "C:\Windows\SysWOW64\FM20.DLL"存储MSForms库的位置,但是它返回一个错误,指出找不到文件或程序集或某些相关文件。

如何在Powershell中获得对MSForms的引用?

编辑:我实际上在VBA中找到了一种替代方法(仅Excel VBA)来解决此问题,而无需将值传递给外部脚本宿主。请看下面。

查看更多

提问者
GuidoT
被浏览
55
GuidoT 2020-02-03 22:41

这是我想出的功能。到目前为止,它似乎可以在Excel中使用所有预定义的枚举和常量以及自定义枚举。该功能必须放置在模块中!

Static Function ParseValue(StringValue) As Variant
    Dim ParseValueBuffer As Variant

    If IsEmpty(ParseValueBuffer) Then
        ParseValueBuffer = 1
        Application.Run ("'ParseValue " & StringValue & "'")
        ParseValue = ParseValueBuffer
        ParseValueBuffer = Empty
    Else
        ParseValueBuffer = StringValue
    End If
End Function

Sub TestMe()
    MsgBox "First line" & ParseValue("vbcrlf") & "Second line"
    MsgBox ParseValue("fmTextAlignCenter") 'Should return "2" (if MSForms is referenced)
    MsgBox ParseValue("rgbblue") 'Should return 16711680
End Sub