【问题标题】:Conversion from type 'Range' to type 'String' is not valid.in vb.net从“范围”类型到“字符串”类型的转换无效。在 vb.net 中
【发布时间】:2019-06-06 20:13:26
【问题描述】:

在调试时单击“下载目录”按钮时出现此错误“从类型“范围”到类型“字符串”的转换无效”。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

【问题讨论】:

  • 我认为你不应该使用“_Default()”函数。我会说它是供内部使用的。 “cellRange.cells(1, 1).Value”怎么样?
  • 如果 Trim(.Cells._cellRange.cells(1, 1).Value) = "" 我这样使用。然后再次发生错误。发生“System.MissingMember Exception”类型的未处理异常.Additional inf:未找到类型“Range”的公共成员“_cellRange”。
  • “cellRange”是您在“.”之前已经拥有的内容。不幸的是,您的代码没有显示您如何获得范围。只需使用“.Cells(1, 1).Value”而不是“.Cells._Default(1,1)”
  • 我将所有默认函数都转换为这个。如果 Trim(.Cells(1, 1).Value) = "" 。但我再次收到此错误“从类型 'Range' 到类型 'String' 的转换无效”。
  • 但在下面的代码中存在...... Private WithEvents exApp As Microsoft.Office.Interop.Excel.Application Private exBook As Microsoft.Office.Interop.Excel.Workbook Private ExSheet As Microsoft.Office .Interop.Excel.Worksheet

标签: vb.net excel-2007


【解决方案1】:

好的,这里是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

【讨论】:

  • 我不能在 Microsoft Visual Basic 2008 中使用 Dim r 作为范围
  • 因为没有定义类型范围,需要导入excel。
  • 导入类型或将其保留为对象。 VB.net 应该没问题。
  • 但是我的代码有...... Private WithEvents exApp As Microsoft.Office.Interop.Excel.Application Private exBook As Microsoft.Office.Interop.Excel.Workbook Private ExSheet As Microsoft.Office。 Interop.Excel.Worksheet
  • 我已经改变了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多