我正在尝试接受来自数据单元格的格式化常量,所以我有一个字符串“xlTotalsCalculationAverage”。如何将其转换为它所代表的Excel常量;常量xlTotalsCalculationAverage
等于整数2.
ActiveSheet.ListObjects(1).ListColumns(RemainingHeader).TotalsCalculation = xlTotalsCalculationAverage
是静态表示。
TargetTotal = something("xlTotalsCalculationAverage")
ActiveSheet.ListObjects(1).ListColumns(RemainingHeader).TotalsCalculation = TargetTotal
是我的目标。
我可以创建一个巨大的case或switch语句,但复制所有可能的值似乎很愚蠢。
如何让Excel将此字符串转换为已知的常量值?
答案 0 :(得分:9)
Sub Tester()
MsgBox WhatIsTheValue("xlTotalsCalculationAverage")
MsgBox WhatIsTheValue("xlTotalsCalculationCountNums")
End Sub
Function WhatIsTheValue(s As String) As Variant
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("modTemp")
Set CodeMod = VBComp.CodeModule
With CodeMod
.DeleteLines 1, .CountOfLines
.InsertLines 1, "Public Function GetEnumVal()"
.InsertLines 2, "GetEnumVal = " & s
.InsertLines 3, "End Function"
End With
WhatIsTheValue = Application.Run("GetEnumVal")
End Function
但实际上 - 不要这样做。
答案 1 :(得分:0)
由于没有真正实用的解决方案,因此您通常无法编写自己的switch语句。由于.NET Interop Libraries和VBA的枚举,据我所知,总是一样的,我编写了一个程序,为(dll)列表中的每个公共枚举生成VBA模块。这是我的Office.Core,PowerPoint,Word,Excel,Publisher和Outlook dll的输出:
https://gitlab.com/jbjurstam/VbaHelpers/tree/master/GenerateVbaEnumHelpers/bin/Release/output
以下是为每个枚举生成的代码示例:
Attribute VB_Name = "wMsoHyperlinkType"
Function MsoHyperlinkTypeFromString(value As String) As MsoHyperlinkType
If IsNumeric(value) Then
MsoHyperlinkTypeFromString = CInt(value)
Exit Function
End If
Select Case value
Case "msoHyperlinkRange": MsoHyperlinkTypeFromString = msoHyperlinkRange
Case "msoHyperlinkShape": MsoHyperlinkTypeFromString = msoHyperlinkShape
Case "msoHyperlinkInlineShape": MsoHyperlinkTypeFromString = msoHyperlinkInlineShape
End Select
End Function
Function MsoHyperlinkTypeToString(value As MsoHyperlinkType) As String
Select Case value
Case msoHyperlinkRange: MsoHyperlinkTypeToString = "msoHyperlinkRange"
Case msoHyperlinkShape: MsoHyperlinkTypeToString = "msoHyperlinkShape"
Case msoHyperlinkInlineShape: MsoHyperlinkTypeToString = "msoHyperlinkInlineShape"
End Select
End Function
不可否认,在你的项目中包含数千个模块是不实际的,但你真的需要这种功能是非常罕见的,所以我只是在特定场合包含我需要的东西。