gpt4 book ai didi

Excel VBA - 在类模块中输入

转载 作者:行者123 更新时间:2023-12-04 20:02:07 26 4
gpt4 key购买 nike

我试图在类模块中使用类型,但我不断收到几个错误。
我曾尝试在“私有(private)”和“公共(public)”之间切换,但无济于事。
谁能给我一个如何在类模块中使用类型的例子?
这就是我正在尝试的:

'Class "clsColor"

Private Type Colors
Red as string
Green as string
Blue as string
End Type

Private Hex as Colors
'_____________________________________________
Private Sub Class_Initialize()
Hex.Red = "FF0000"
Hex.Green = "00FF00"
Hex.Blue = "0000FF"
End Sub
'Regular Module

msgbox clsColor.Hex.Red
我该怎么做才能使这种类型在类模块中工作?
或者创建一个额外的类而不是类型是更好的做法?

最佳答案

Brian M Stafford 提出了一种二分类方法,指出:“Type 在这种情况下不能使用”,当
您想将不同的颜色设置为 对象属性 .Hex ,例如通过

MyColor.Hex.Blue    

"Can anyone provide me an example of how to use a Type inside a Class Module?"


如果将所需颜色作为 ►variant 传递,它可能会使调用更流畅,而不是连续的对象层次结构。论据 .Hex只要。
在这种情况下,您不需要相关类(class),并且可以从 Type 中获利。 (和 Enum )定义
允许获得想要的结果,例如via(枚举常量)
MyColor.Hex(Blue)      ' or via VBA.ColorConstants: MyColor.Hex(vbBlue)
' or via string input: MyColor.Hex("Blue")
类颜色 - 标题定义 ( Enum , Type )
Option Explicit

Enum ColorSynonyms
[_Start] = -1
'equivalents to the 8 VBA.ColorConstants (vbBlack, vbRed..)
Black
Red
Green
Yellow
Blue
Magenta
Cyan
White
'---user defined constants
Brown
Grey
Orange
End Enum

Private Type THexColors
Red As String
Green As String
Blue As String
End Type

Private HexColors As THexColors
类(class)颜色 - 进一步的代码
Private Sub Class_Initialize()
With HexColors
.Blue = "0000FF"
.Green = "00FF00"
.Red = "FF0000"
End With
End Sub

Public Property Get Hex(currColor) As String
Select Case currColor
Case "Red", Red, vbRed
Hex = HexColors.Red
Case "Green", Green, vbGreen
Hex = HexColors.Green
Case "Blue", Blue, vbBlue
Hex = HexColors.Blue
Case Else
Hex = "Undefined!"
End Select
End Property
示例电话
Private Sub Test()
Dim MyColor As Color
Set MyColor = New Color
Debug.Print "Blue", MyColor.Hex(Blue)

'alternatively:
Debug.Print "Blue", MyColor.Hex(vbBlue)
Debug.Print "Blue", MyColor.Hex("Blue")
End Sub

关于Excel VBA - 在类模块中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68834576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com