Option Strict On禁止来自' String'的隐式转换。到' Double'

时间:2017-01-13 16:34:01

标签: vb.net excel-interop

1-创建一个excel文件,如C:\ MyFolder \ Book1.xlsx。

2-运行以下代码,看看代码是否正常运行。

Option Strict Off
Imports Microsoft.Office.Interop

Public Class Form1
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    DateTimePicker1.Value = CDate(CStr(System.DateTime.Now.AddDays(-System.DateTime.Now.Day)))

    Dim xlApp As New Excel.Application
    xlApp.WindowState = Excel.XlWindowState.xlMinimized

    Dim wb1 As Excel.Workbook
    wb1 = xlApp.Workbooks.Open("C:\MyFolder\Book1.xlsx")

    Dim ws1 = CType(wb1.Sheets(1), Excel.Worksheet)

    With ws1
        .Range("A1").Value = "2017"
        If .Range("A1").Value.ToString <> CDbl(DateTimePicker1.Value.ToString("yyyy")) Then
            MsgBox("error")
        End If
    End With

End Sub

End Class

5-当我打开Option Strict On时,我有错误。

1 个答案:

答案 0 :(得分:1)

您希望将ws.Range("A1").Value的字符串表示形式与DateTimePicker1.Value的字符串表示形式进行比较。

DateTimePicker1.Value转换为Double似乎很奇怪。这就是编译器显示错误的原因,因为代码

.Range("A1").Value.ToString <> CDbl(DateTimePicker1.Value.ToString("yyyy"))

会尝试将string类型的值与double类型的值进行比较,Strict Option On不允许这样做。

只需比较字符串而不转换为double

If .Range("A1").Value.ToString() <> DateTimePicker1.Value.ToString("yyyy") Then
    MsgBox("error")
End If