索引超出范围必须小于或为负

时间:2018-12-12 06:19:58

标签: excel vb.net

我对该索引有问题,超出范围,我真的不知道该怎么解决。这是代码。

Sub insert()
    Dim dt As DataTable

    Try

        For i As Integer = 0 To DataGridView1.Rows.Count - 1
            exec("select * from TBL_SUMMARY1")
            dt = exec("insert into TBL_SUMMARY1 values('" & DataGridView1.Rows(i).Cells(0).Value & "','" & DataGridView1.Rows(i).Cells(1).Value & "','" & DataGridView1.Rows(i).Cells(2).Value & "','" & DataGridView1.Rows(i).Cells(3).Value & "','" & DataGridView1.Rows(i).Cells(4).Value & "','" & DataGridView1.Rows(i).Cells(5).Value & "','" & DataGridView1.Rows(i).Cells(6).Value & "','" & DataGridView1.Rows(i).Cells(7).Value & "','" & DataGridView1.Rows(i).Cells(8).Value & "','" & DataGridView1.Rows(i).Cells(9).Value & "','" & DataGridView1.Rows(i).Cells(10).Value & "','" & DataGridView1.Rows(i).Cells(11).Value & "','" & DataGridView1.Rows(i).Cells(12).Value & "','" & DataGridView1.Rows(i).Cells(13).Value & "','" & DataGridView1.Rows(i).Cells(14).Value & "','" & DataGridView1.Rows(i).Cells(15).Value & "','" & DataGridView1.Rows(i).Cells(16).Value & "','" & DataGridView1.Rows(i).Cells(17).Value & "','" & DataGridView1.Rows(i).Cells(18).Value & "','" & DataGridView1.Rows(i).Cells(19).Value & "','" & DataGridView1.Rows(i).Cells(20).Value & "','" & DataGridView1.Rows(i).Cells(21).Value & "','" & DataGridView1.Rows(i).Cells(22).Value & "','" & Date.Today & "' )")

        Next
        MetroFramework.MetroMessageBox.Show(Me, "Insert Successfuly")
        TextBox1.Text = ""

        DataGridView1.Columns.Clear()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

在导入某些excel文件并隐藏其他数据时也在此处。

 Dim op As New OpenFileDialog
    Dim partfile As String
    Try
        op.Filter = "XlS Files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xlsx"
        If op.ShowDialog = DialogResult.OK Then
            TextBox1.Text = op.FileName
            partfile = TextBox1.Text

            con = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source= '" & partfile & "';Extended Properties=""Excel 12.0 Xml;HDR = yes""")
            da = New OleDbDataAdapter("Select * from [Summary$]", con)
            da.TableMappings.Add("Table", "Myfile")
            ds = New DataSet
            da.Fill(ds)
            ds.Tables(0).Rows.RemoveAt(0)
            ds.Tables(0).Rows.RemoveAt(0)
            ds.Tables(0).Rows.RemoveAt(0)
            DataGridView1.DataSource = ds.Tables(0)
            DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
            DataGridView1.Refresh()
            con.Close()
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

导入后,将弹出Sample error

2 个答案:

答案 0 :(得分:0)

您必须确定数据库中的列数,必须在计数中包括列索引(0) 确认列数之后,必须确保()中的列数等于数据库表中的列数或更少,并且不存在彼此之间的值冲突或变量类型不同

否则 给我一张数据库表的图片

答案 1 :(得分:0)

这个问题已经解决,我只是通过在Excel中将Excel从旧数据保存到新数据来解决此问题。我不知道这是否可以解决其他问题。