-
我的问题是根据";C"c";,或";F"f";在数字的末尾。例如,如果输入用户输入32f或32f,则消息框显示0C,反之亦然。
-
这是我的代码:
Sub Conversion()
Dim temp As String
temp = Val(InputBox("Enter the Temperature followed by F for Fahrenheit or C for Celsius"))
Dim f As String
Dim c As String
Dim Conversion As String
f = ((9 * temp) / (5 + 32))
c = ((temp - 32) * (5 / 9))
Conversion = InStr(1, temp, "c")
If temp = True Then
f = ((9 * temp) / (5 + 32))
MsgBox ("Temperature in F is" & f)
Else
c = ((temp - 32) * (5 / 9))
MsgBox ("Temperature in C is " & c)
End If
End Sub
根据评论
- f和c应该是双
- Val将删除您尝试测试的文本。所以创建一个新的变量来保存这个数字
- 确保使用
vbTextCompare
来确保匹配,无论情况如何 - 测试
Conversion
而非temp
- 华氏度的公式把
()
放错了地方
Sub Conversion()
Dim temp As Variant
temp = InputBox("Enter the Temperature followed by F for Fahrenheit or C for Celsius")
Dim tempNum As Double
tempNum = Val(temp)
Dim f As Double
Dim c As Double
Dim Conversion As String
Conversion = InStr(1, temp, "c", vbTextCompare)
If Conversion > 0 Then
f = ((9# * tempNum / 5) + 32)
MsgBox "Temperature in F is" & f
Else
c = ((tempNum - 32#) * (5 / 9))
MsgBox "Temperature in C is " & c
End If
End Sub
您发布的代码存在各种问题。下面是使用Ucase、Left、Mid和Right的示例。
Sub Conversion()
Dim temp As String
Dim retVal As String
temp = InputBox("Enter the Temperature followed by F for Fahrenheit or C for Celsius")
If (UCase(Right(Trim(temp), 1))) = "C" Then
retVal = "Temperature in C is " & ((9 * CInt(Left(temp, Len(temp) - 1))) / 5 )+ 32)
ElseIf (UCase(Right(Trim(temp), 1))) = "F" Then
retVal = "Temperature in F is " & ((CInt(Left(temp, Len(temp) - 1)) - 32) * (5 / 9))
Else
retVal = "Could not determine Fahrenheit or Celsius for the input value: " & temp
End If
MsgBox retVal
End Sub
您的代码不是主要问题;你的计算错了。
从摄氏度到华氏度的换算为(n*9/5(+32。你在做(n*9(/(5+32(。
您还立即排除了结果的文本部分;所选择的单元不会存储在任何地方。
Sub ConversionV2()
Dim strInput As String
Dim dblTemp As Double
strInput = InputBox("Enter the Temperature followed by F for Fahrenheit or C for Celsius")
dblTemp = Val(strInput)
Select Case UCase(Right(strInput, 1))
Case Is = "C"
MsgBox ("Temperature in F is " & ((dblTemp * 9) / 5) + 32)
Case Is = "F"
MsgBox ("Temperature in C is " & ((dblTemp - 32) * 5) / 9)
Case Else
MsgBox "Sorry, I didn't recognise that input"
End Select
End Sub
将整个输入存储为字符串可以让我们更容易地执行操作。我们可以从字符串中提取VAL,并且我们可以查看最后一个字符来查看要使用的转换。此外,使用Select语句可以让我们控制不止两个预期结果。
进行不需要的计算也是不好的做法;如果我们只使用F和C中的一个,则不需要同时存储它们。将计算放入Select语句可确保只执行必要的计算。