首页 > 解决方案 > 从“范围”类型到“字符串”类型的转换无效。在 vb.net 中

问题描述

在调试此错误时单击“下载目录”按钮会发生“从类型“范围”到类型“字符串”的转换无效”。Microsoft.VisualBasic 中发生了“System.InvalidCastException”类型的未处理异常。

        If Trim(.Cells._Default(1, 1)) = "" Then
            MsgBox("Please Enter the Auction No in Cell B2 ", MsgBoxStyle.Information)
            Exit Function
        Else

            StrAuctionNo = Trim(.Cells._Default(1, 1))
        End If

标签: vb.netexcel-2007

解决方案


好的,这是 Vb.net 版本:

Public Sub Test()
    dim excel as new Microsoft.Office.Interop.Excel.Application
    Dim workbook As Microsoft.Office.Interop.Excel.Workbook
    Dim cellRange As Microsoft.Office.Interop.Excel.Range
    Dim sheet As Microsoft.Office.Interop.Excel.Worksheet

    workbook = excel.Workbooks.Open("c:\temp\Book1.xls")

    sheet = workbook.Sheets(1)
    cellRange = sheet.Range("A1:B2")
    Dim val As String = cellRange.Cells(2,2).Value

    If String.IsNullOrEmpty(val) orelse val.Trim() = String.Empty Then
        MsgBox("Field missing ....")
    Else 
        MsgBox("OK!!")
    End If

End Sub

推荐阅读