我需要将字符串转换为数值。
我的字符串不是数字。我在程序中定义了此字符串的数值。
这是我正在执行的测试:
Sub TestFinal()
Dim Result As Integer
Dim StartNumber As Integer
Dim EndNumber As Integer
Dim b As Variant
Dim d As Variant
Dim ValCellY As String
Dim ValCellZ As String
StartNumber = 2 'First line value of my table
EndNumber = 3 'Last line value of my table
b = 80
d = 20
For StartNumber = 2 To EndNumber 'Begining of my loops
ValCellY = Cells(StartNumber, 2).Value
ValCellZ = Cells(StartNumber, 3).Value
If Cells(StartNumber, 1) = "Yes" Then 'First if condition
Result = 100
End If
If Cells(StartNumber, 1) = "No" Then 'Second if condition
'I use CInt function to convert my string into a integer
Result = 75 * CInt(ValCellY) + 25 * CInt(ValCellZ)
End If
'I associate the varaible Result to the column D
Cells(StartNumber, 4).Value = Result
Next StartNumber 'End of my loops
End Sub
我不明白为什么不考虑值 b 和 d 。 此外,还会显示错误消息:“类型不匹配”。
答案 0 :(得分:0)
将它们转换回变量。
ValCellY = IIf(Cells(StartNumber, 2).Value = "b", b, d)
ValCellZ = IIf(Cells(StartNumber, 3).Value = "b", b, d)
答案 1 :(得分:0)
您正在使用字符串而不是实际值进行计算。您可以使用if或select case,但如果实际问题更复杂,则建议使用字典。
Option Explicit
Sub TestFinal()
Dim Result As Integer
Dim StartNumber As Integer
Dim EndNumber As Integer
Dim b As Variant
Dim d As Variant
Dim ValCellY As String
Dim ValCellZ As String
StartNumber = 2 'First line value of my table
EndNumber = 3 'Last line value of my table
b = 80
d = 20
For StartNumber = 2 To EndNumber 'Begining of my loops
ValCellY = Cells(StartNumber, 2).Value
ValCellZ = Cells(StartNumber, 3).Value
If Cells(StartNumber, 1) = "Yes" Then 'First if condition
Result = 100
End If
If Cells(StartNumber, 1) = "No" Then 'Second if condition
If ValCellY = "b" Then
ValCellY = b
ElseIf ValCellY = "d" Then
ValCellY = d
End If
If ValCellZ = "b" Then
ValCellZ = b
ElseIf ValCellZ = "d" Then
ValCellZ = d
End If
Result = 75 * CInt(ValCellY) + 25 * CInt(ValCellZ) 'I use CInt function to convert my string into a integer
End If
Cells(StartNumber, 4).Value = Result 'I associate the varaible Result to the column D
Next StartNumber 'End of my loops
End Sub