选择正确的私人子

时间:2018-11-19 23:23:52

标签: excel vba excel-vba

我有一些可用于控制按钮的VBA代码。该代码工作正常,但我希望它可以自动运行。我似乎无法正确理解Private Sub。代码如下:

Private Sub CommandButton3_Click()

Dim num As String

num = Range("L5").Value

Select Case num

        Case Is = 15, 16, 17, 18, 19

            Range("X5").Value = "510"

        Case Is = 20, 21, 22, 23, 24

            Range("X5").Value = "570"

        Case Is = 25, 26, 27, 28, 29

            Range("X5").Value = "610"

        Case Is = 30, 31, 32, 33, 34

            Range("X5").Value = "630"

        Case Is = 35, 36, 37, 38, 39

            Range("X5").Value = "635"

        Case Is = 40, 41, 42, 43, 44

            Range("X5").Value = "632"

        Case Is = 45, 46, 47, 48, 49

            Range("X5").Value = "622"

        Case Is = 50, 51, 52, 53, 54

            Range("X5").Value = "610"

        Case Is = 55, 56, 57, 58, 59

            Range("X5").Value = "590"

        Case Is = 60, 61, 62, 63, 64

            Range("X5").Value = "565"

        Case Is = 65, 66, 67, 68, 69

            Range("X5").Value = "540"

        Case Is = 70, 71, 72, 73, 74

            Range("X5").Value = "520"

        Case Is = 75, 76, 78, 79

            Range("X5").Value = "490"

        Case Is = 80, 81, 82, 83, 84

            Range("X5").Value = "470"

        Case Is = 85, 86, 87, 88, 89, 90

            Range("X5").Value = "440"

 End Select

 End Sub

2 个答案:

答案 0 :(得分:1)

创建用户定义的函数,并根据"X5"的内容使用它来更新"L5"

在模块中编写以下代码:

Public Function MyFunction(ByVal value As Double) As Double
    Dim x As Long, y As Long
    x = CLng(value)
    Select Case x
        Case 15 To 19
            y = 510
        Case 20 To 24
            y = 570
        Case 25 To 29
            y = 610
        Case 30 To 34
            y = 630
        Case 35 To 39
            y = 635
        Case 40 To 44
            y = 632
        Case 45 To 49
            y = 622
        Case 50 To 54
            y = 610
        Case 55 To 59
            y = 590
        Case 60 To 64
            y = 565
        Case 65 To 69
            y = 540
        Case 70 To 74
            y = 520
        Case 75 To 79
            y = 490
        Case 80 To 84
            y = 470
        Case 85 To 90
            y = 440
        Case Else
            y = 0
    End Select
    MyFunction = CDbl(y)
End Function

结果将自动更新。

scr

答案 1 :(得分:1)

您不需要case语句,因为您的方括号以统一的方式递增,所以您可以用1行代码(加上一个if来捕获范围之外的任何内容)来完成它:

Public Function MyFunction2(ByVal MyValue As Double) As Double
If MyValue < 15 Or MyValue > 90 Then
    MyFunction2 = 0
Else
    MyFunction2 = CDbl(Array(0, 0, 0, 510, 570, 610, 630, 635, 632, 622, 610, 590, 565, 540, 520, 490, 470, 440)(Round(MyValue / 5, 0)))
End Function

这是一个UDF,因此遵循与ja72的回答相同的逻辑,但是放MyFunction2而不是MyFunction,并排放置它们,以便您可以比较它们都给出相同的结果。