2016-08-11 139 views
1

在vb.net中创建应用程序以连接到Excel文件并对其进行编辑。向excel提出查询时出现奇怪的错误

目前试图修改Excel文件时,出现以下错误:

有了这个功能

Protected Friend Function obtenerHojaActual(ByVal columna As String, ByVal con As String) As String 
    Dim cmd As String 
    Dim WorkSheet As String = "" 
    Try 
     libro = app.Workbooks.Open(con) 
     For Each hoja As Microsoft.Office.Interop.Excel.Worksheet In libro.Worksheets 
      cmd = "SELECT [" & columna & "] FROM [" & hoja.Name & "$]" 
      Dim adapter As New OleDbDataAdapter(cmd, conexion) 
      Dim tabla As New DataTable 
      adapter.Fill(tabla) 
      adapter.Dispose() 
      //Code 
      //Code 
      //Code 
      tabla.Dispose() 
     Next 
     libro.Close() 
     app.Quit() 
     Return WorkSheet 
    Catch ex As Exception 
     repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog() 
     principal.lbldireccion.ForeColor = Color.Red 
     Return WorkSheet 
    End Try 
End Function 

得到这个:

enter image description here

“没有指定的值对于一些所需的参数“

而与此:

Protected Friend Function obtenerErrores(ByVal columna As String, ByVal hoja As String, ByVal tipo As String) As Integer 
    Dim cmd As String = "SELECT [" & columna & "] FROM [" & hoja & "$]" 
    Dim errores As Integer = 0 
    Dim fecha As Date 
    Dim tabla As New DataTable 
    Try 
     Dim adapter As New OleDbDataAdapter(cmd, conexion) 
     adapter.Fill(tabla) 
     adapter.Dispose() 
     //Code 
     //Code 
     //Code 
     tabla.Dispose() 
     Return errores 
    Catch ex As Exception 
     repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog() 
     principal.lbldireccion.ForeColor = Color.Red 
     Return errores 
    End Try 

得到这个错误...

enter image description here

我尝试使用参数化查询,但看起来像Excel中不要工作得很好用那个东西(也许,我不知道用于Excel的查询的语法)。

最奇怪的是,在代码的其他部分,不要给我错误,程序只是在我试图修改文件时抛出错误,尽管我得到这两个错误,但excel表单被修改就像我想要的那样。

什么可以是?

+0

你在你的'Exception'对象有一个'InnerException'?那些通常会告诉你什么参数丢失。 –

+0

不...让我添加它,看看 – TwoDent

+0

我插入了你告诉我的内容,并打印出一个空白的msgbox ... – TwoDent

回答

0

好吧,我坐下来检查一切,我不得不想一想发生了什么。我发现我的代码没有任何错误(这就是为什么即使程序给我错误,文件也会被修改)...并且也发现了这个问题,让我用Excel文件示例来解释它:

enter image description here你可以看到,我使用我的连接字符串HDR属性(“HDR =是;”表示第一行包含列名,而不是数据。“HDR =否;”表示正好相反,)已经定义了4列(姓名,姓氏,日期,年龄...不多!)。

我们与此示例文件现在运行程序,并仔细看会发生什么:

enter image description here

正如我们在第一张图片所看到的,我从来没有在这个位置(“F1”创建了一列)...显然,有些时候你在Excel中没有意识到我称之为“虚幻列”。我想这是因为该列的第一个单元格没有写入任何内容,程序会根据它们的位置自动给出它的名称('F1'是幽灵列)。

要解决此问题,当我进行查询时,首先检查我的参数“列”是否为空。

Protected Friend Function obtenerHojaActual(ByVal columna As String, ByVal con As String) As String 
    If (Not String.IsNullOrEmpty(columna)) Then 
     //Blah blah 
     //Blah blah 
     //Blah blah 
    End If 
    Return "Desconocida" 
End Function 

然后我们开始吧!

enter image description here

相关问题