VBA复选框:需要优雅的解决方案

时间:2012-10-30 13:31:24

标签: vba

我遇到了VBA问题,我们正在寻找一种快速而优雅的解决方案。

问题涉及复选框:选择和取消选择。

假设我们从一行和四列数据开始(单元格A1:A4:

A   B   Star    D

我们有三个未经检查的框:GalaxyUniversePlanet

检查Galaxy后,该行被动态复制(到下一个空行)

A   B   Star    D
A   B   Galaxy  D

如果我们检查所有三个:

A   B   Star    D
A   B   Galaxy  D
A   B   UniverseD
A   B   Planet  D

现在,如果我们取消选中Universe ..该行自动被省略为:

A   B   Star    D
A   B   Galaxy  D
A   B   Planet  D

我喜欢实时',因为你看到它'感觉这样的设置。有没有一种优雅的方法我不能用来编码呢?

非常感谢提前。

1 个答案:

答案 0 :(得分:0)

Function GetDataBasedOnSelection(ByVal galaxyChecked As Boolean, ByVal universeChecked As Boolean, _
ByVal planetChecked As Boolean) As Variant
Dim currentRow As Integer
Dim retVal(1 To 3, 1 To 4)

currentRow = 1
If galaxyChecked Then
    GoSub fillInCommonValuesInThisRow
    retVal(currentRow, 3) = "Galaxy"
    currentRow = currentRow + 1
End If

If universeChecked Then
    GoSub fillInCommonValuesInThisRow
    retVal(currentRow, 3) = "Universe"
    currentRow = currentRow + 1
End If

If planetChecked Then
    GoSub fillInCommonValuesInThisRow
    retVal(currentRow, 3) = "Planet"
    currentRow = currentRow + 1
End If

GetDataBasedOnSelection = retVal
Exit Function

fillInCommonValuesInThisRow:
    retVal(currentRow, 1) = "A"
    retVal(currentRow, 2) = "B"
    retVal(currentRow, 3) = ""
    retVal(currentRow, 4) = "D"
Return
End Function

如何使用上述方法:

'Pass the actual selection (true if the checkbox is checked, false otherwise)
Range("A2:D4").Value = GetDataBasedOnSelection(True, False, True)