【发布时间】:2019-10-10 11:25:39
【问题描述】:
我正在创建一个条件格式工具。用户完成一个电子表格,描述他们想要添加的格式和位置。
我的 VBA 用列索引号标记此电子表格中的每一列,并在循环遍历每一行时将每个元素传递给 VBA。
此语句(如下)出现类型不匹配错误,我发现问题是在格式条件方法中为规则类型和运算符参数传递枚举; VBA 将其作为文本读取,而从研究中我了解到枚举本质上是文本形式的长类型(?)。
Sub s_ApplyFormats()
Dim rng_FormattingInfo As Range
Dim rng_RowItem As Range
Const int_VBAFormatTypeCol As Integer = 2 'xlCellValue or xlExpression
Const int_VBAOperatorCol As Integer = 4 'xlEqual, xlBetween, etc.
Const int_FormulaCol As Integer = 5
Const int_WorksheetCol As Integer = 6
Const int_RangeCol As Integer = 7
Const int_FormatCol As Integer = 8
Const int_StopIfTrueCol As Integer = 10
'The column numbers of the relevant columns in the Conditional Formatting admin worksheet
Set rng_FormattingInfo = Range("rng_ConditionalFormattingData")
'Contains all columns in the Conditional Formatting admin worksheet
For Each rng_RowItem In rng_FormattingInfo.Rows
With Worksheets(rng_RowItem.Cells(int_WorksheetCol).Value2) _
.Range(rng_RowItem.Cells(int_RangeCol)).FormatConditions _
.Add(rng_RowItem.Cells(int_VBAFormatTypeCol).Value2, rng_RowItem.Cells(int_VBAOperatorCol).Value2, _
rng_RowItem.Cells(int_FormulaCol))
.Font.ColorIndex = rng_RowItem.Cells(int_FormatCol).Font.ColorIndex
.Interior.ColorIndex = rng_RowItem.Cells(int_FormatCol).Interior.ColorIndex
End With
Next rng_RowItem
End Sub
作为一个潜在的解决方案,我可以在工作簿中创建一个查找,这样当用户在电子表格中选择“xlCellValue”时,枚举值 (1) 会被传递给 VBA。这需要我列出每个枚举的字符串和数字形式。
但是,有没有办法可以将枚举的字符串形式从单元格传递到 VBA?
【问题讨论】:
-
你能提供一份你的工作表样本吗?
-
回答您的明确问题:不,VBA 不能使用字符串进行枚举。它需要某种“查找”,无论是在代码中,还是在您提到的工作表或其他来源中。
-
@CindyMeister - 这回答了我的问题,谢谢。
-
附带说明,不要使用
Integer,而更喜欢在VBA 中使用Long。原因是Integer是 16 位,Long是 32 位。您可以安全地用 Long 替换每个 Integer 实例,除非 API 明确需要Integer。
标签: excel vba string text enumeration