vb.net 错误:Option Strict On 不允许从“对象”到“十进制”的隐式转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17243679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:59:48  来源:igfitidea点击:

Error: Option Strict On disallows implicit conversions from 'Object' to 'Decimal'

vb.net

提问by Jose M.

I am tying to check the value of cell J34 (excel). If that value is null then display message, if not run the rest of the code.

我要检查单元格 J34 (excel) 的值。如果该值为空,则显示消息,否则运行其余代码。

However, when I am compiling I get the error above on line:

但是,当我编译时,我在线上收到上面的错误:

decAnnualMid = Convert.ToDecimal(Globals.dsbPositionBoard.Range("J34").Value)

decAnnualMid = Convert.ToDecimal(Globals.dsbPositionBoard.Range("J34").Value)

Here is the rest of my code

这是我的其余代码

Option Strict On
Option Explicit On

Private Sub chk10thPercentile_CheckedChanged(sender As Object, e As EventArgs) Handles chk10thPercentile.CheckedChanged
    'This event runs when the 10th checkbox is checked
    'The event clears the cells where the value will be pasted
    'enters the value from cell J34 into calculationShet H45 and clears
    'the checkboxes for 25th, 50th, 75th, 90th and Other Amount
    'checkboxes.

    Dim decAnnualMid As Decimal
    If chk25thPercentile.Checked = True And Globals.dsbPositionBoard.Range("J34").Value Is DBNull.Value Then
        'Display is user has not selected a position in the dashboard.
        MsgBox("The Market Data section of the Position Dashboard does not have a value for the 10th Percentile.", MsgBoxStyle.Critical, "Input Error")
        Me.Close()
    Else
        'convert the value of K34 to decimal and
        decAnnualMid = Convert.ToDecimal(Globals.dsbPositionBoard.Range("J34").Value)


        'convert annual salary to hourly
        decHourlyMid = decAnnualMid / 52 / 40

        'display in the Mid label box
        lblAnnualMid.Text = decAnnualMid.ToString("C")
        lblHourlyMid.Text = decHourlyMid.ToString("C")

        'Uncheck all other boxes

        chk25thPercentile.Checked = False
        chk50thPercentile.Checked = False
        chk75thPercentile.Checked = False
        chk90thPercentile.Checked = False
        chkOtherAmount.Checked = False
    End If
End Sub

回答by Hans Passant

Range("J34") produces an object reference of type Object, not Range. You'll have to cast to keep Option Strict On happy:

Range("J34") 产生一个 Object 类型的对象引用,而不是 Range。您必须进行强制转换才能让 Option Strict On 满意:

Dim sel As Range = CType(Globals.dsbPositionBoard.Range("J34"), Range)
decAnnualMid = Convert.ToDecimal(sel.Value)