我是VBA的新手,目前正在使用它创建一个使用三个条件来吐出计算结果的函数。三个输入单元格包括一个数值("排放量")和两个文本值(" gas""单位",两者都具有从中选择的值下拉菜单。
我基本上想要创建一个根据从下拉菜单中选择的值计算结果的函数。例如,如果下拉B(" gas")列出某个值并下拉C"单位"列出了某种类型的单位测量,我想用A列中的数量来计算最终值。这是我到目前为止开始开发的(对于三种污染物类型中的一种):
Function CO2EquivalentEmissions(emissionsquantity As Double, gas As String, units As String)
If (gas = "CH4" Or "ch4") And units = "tons" Then
CO2EquivalentEmissions = emissionsquantity * 25
ElseIf (gas = "CH4" Or "ch4") And units = "lbs" Then
CO2EquivalentEmissions = (emissionsquantity / 2000) * 25
ElseIf (gas = "CH4" Or "ch4") And units = "tonnes" Then
CO2EquivalentEmissions = (emissionsquantity * 1.10231) * 25
End If
End Function
然而,使用此函数,我得到0.00的结果,无论我使用哪个值" emissionquantity"。有什么建议?非常感谢!
答案 0 :(得分:2)
您对如何测试字符串感到困惑,您错放了"
的位置,请参阅下面的代码:
Function CO2EquivalentEmissions(emissionsquantity As Double, gas As String, units As String)
If gas = "CH4" And units = "tons" Then
CO2EquivalentEmissions = emissionsquantity * 25
ElseIf gas = "CH4" And units = "lbs" Then
CO2EquivalentEmissions = (emissionsquantity / 2000) * 25
ElseIf gas = "CH4" And units = "tonnes" Then
CO2EquivalentEmissions = (emissionsquantity * 1.10231) * 25
End If
End Function
修改1 :更新后的更正Function
(气体标准包含Or
Function CO2EquivalentEmissions(emissionsquantity As Double, gas As String, units As String)
If (gas = "CH4" Or gas = "ch4") And units = "tons" Then
CO2EquivalentEmissions = emissionsquantity * 25
ElseIf (gas = "CH4" Or gas = "ch4") And units = "lbs" Then
CO2EquivalentEmissions = (emissionsquantity / 2000) * 25
ElseIf (gas = "CH4" Or gas = "ch4") And units = "tonnes" Then
CO2EquivalentEmissions = (emissionsquantity * 1.10231) * 25
End If
End Function
答案 1 :(得分:1)
OR条件中有一个小错误。要么这样做:
Function CO2EquivalentEmissions(emissionsquantity As Double, gas As String, units As String)
If (gas = "CH4" Or gas = "ch4") And units = "tons" Then
CO2EquivalentEmissions = emissionsquantity * 25
ElseIf (gas = "CH4" Or gas = "ch4") And units = "lbs" Then
CO2EquivalentEmissions = (emissionsquantity / 2000) * 25
ElseIf (gas = "CH4" Or gas = "ch4") And units = "tonnes" Then
CO2EquivalentEmissions = (emissionsquantity * 1.10231) * 25
End If
End Function
或者包含选项比较文本,这将使所有"文本比较"不区分大小写,因此您可以简单地进行单一检查,这将适用于CH4,cH4等:
Option Compare Text
Function CO2EquivalentEmissions(emissionsquantity As Double, gas As String, units As String)
If (gas = "ch4") And units = "tons" Then
CO2EquivalentEmissions = emissionsquantity * 25
ElseIf (gas = "ch4") And units = "lbs" Then
CO2EquivalentEmissions = (emissionsquantity / 2000) * 25
ElseIf (gas = "ch4") And units = "tonnes" Then
CO2EquivalentEmissions = (emissionsquantity * 1.10231) * 25
结束如果 结束功能