首页 > 解决方案 > 如何在 VBA 中编写日志功能?

问题描述

我的教授给了我们一个编写函数的练习,它可以显示你的孩子是否在成长。唯一的问题是他并没有真正向我们解释 VBA。所以到目前为止我想出的所有东西都是在网上学到的。你们能看看我的功能并指出我的失败吗?我知道逻辑应该有效,但我认为我在 VBA 的语法上犯了一些错误。

非常感谢下面的代码。

Dim months As Integer
Dim height As Double
Dim p1, p2, p3, p4 As Double
Dim message As String
childgroup = message
months = months / 100
p1 = 0
p2 = 0
p3 = 0
p4 = 0

p1 = Application.WorksheetFunction.Log(months + 1, 20) + 0.3 / months
p2 = Application.WorksheetFunction.Log(months + 1, 30) + 0.3 / months
p3 = Application.WorksheetFunction.Log(months + 1, 40) + 0.3 / months
p4 = Application.WorksheetFunction.Log(months + 1, 50) + 0.3 / months

If p2 <= height <= p1 Then message = "green"
ElseIf p3 <= height < p2 Then
message = "orange"
Else: message = "red"
End If

End Function```

标签: excelvba

解决方案


您要检查的公式是什么?当前的 p1-p4 值对我来说没有意义。对您的代码的升级,部分基于您在下面的帖子下方的评论。一些基本的注释:

  • 在代码中添加注释,注释以单引号开头
  • 给变量一些有意义的名字,比如“age_months”和“months”

希望这可以帮助。

Sub test_this_function()

    Debug.Print growing_status(12, 0.8)
    Debug.Print growing_status(24, 0.8)

End Sub

Function growing_status(age_months As Integer, height_m As Double) As String

Dim p1 As Double, p2 As Double, p3 As Double, p4 As Double
Dim message As String

p1 = 0
p2 = 0
p3 = 0
p4 = 0

childgroup = message 'what does this do? seems without use
months_two = age_months / 100 'why this, months_two is now a double?

Debug.Print Application.WorksheetFunction.Log(age_months + 1, 40)

p1 = Application.WorksheetFunction.Log(months_two + 1, 20) + 0.3 / months_two
p2 = Application.WorksheetFunction.Log(months_two + 1, 30) + 0.3 / months_two
p3 = Application.WorksheetFunction.Log(months_two + 1, 40) + 0.3 / months_two
p4 = Application.WorksheetFunction.Log(months_two + 1, 50) + 0.3 / months_two

If p2 <= height_m And height_m <= p1 Then
    message = "green"
ElseIf p3 <= height_m And height_m < p2 Then
    message = "orange"
Else
    message = "red"
End If

growing_status = message

End Function

推荐阅读