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时,我有错误。
答案 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