Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在VBA中按名称解析枚举值_Vba_Forms_Powershell - Fatal编程技术网

在VBA中按名称解析枚举值

在VBA中按名称解析枚举值,vba,forms,powershell,Vba,Forms,Powershell,我想编写一些VBA代码,将MSForms常量名称(以字符串形式给出,如“fmTextAlignLeft”)解析为它们的实际值。由于没有本机方法可以这样做,我正在考虑将常量的名称放入powershell代码中,然后执行该代码并返回结果 Private Sub ParseEnumByName(EnumConst As String) Dim WScript As New WshShell Dim PSCode As String Dim Result PSCode =

我想编写一些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库完全不同

我试图
添加类型-路径“C:\Windows\SysWOW64\FM20.DLL”
,其中存储MSForms库,但它返回一个错误,表示找不到文件或程序集或某些相关文件

如何在Powershell中获取对MSForms的引用


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

这是我计算出的函数。到目前为止,它似乎可以处理所有预定义的枚举和常量,以及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

鉴于枚举表单MSForms不太可能改变那么多,您可以将值硬编码到数组或其他形式的程序中。这并不比启动外部powershell进程并运行脚本进行查找更糟糕。您甚至可以使用powershell脚本生成嵌入到程序中的硬编码值。请参阅下面的答案。