自动增量ID Excel VB.NET

时间:2018-09-17 03:47:32

标签: excel vb.net auto-increment

当我向excel中插入新数据时,我想自动递增ID,这是我的代码

当我使用此代码时,它会自动递增,但是当excel工作表没有任何ID输入却不起作用

Try
        cn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Users\\Barbatos\\Desktop\\Book1.xlsx " + ";Extended Properties=Excel 12.0;")
        cn.Open()
        cm = New OleDbCommand("SELECT MAX([ID]) FROM [Sheet1$]", cn)

        Dim dr As OleDbDataReader = cm.ExecuteReader
        If dr.Read = True Then
            Me.IDEm.Text = dr.Item(0) + 1
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    cn.Close()

但是当我使用此代码时,即使excel工作表尚无任何ID输入,它也会自动递增,但只能递增10,并在10处停止

Try
        cn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Users\\Barbatos\\Desktop\\Book1.xlsx " + ";Extended Properties=Excel 12.0;")
        cn.Open()
        cm = New OleDbCommand("SELECT MAX([ID]) AS MAXIMUM FROM [Sheet1$]", cn)

        Dim dr As OleDbDataReader = cm.ExecuteReader
        If dr.Read = True Then
            If IsDBNull(dr("MAXIMUM")) Then
                Me.IDEm.Text = 1
            Else
                Me.IDEm.Text = dr.Item(0) + 1
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    cn.Close()
End Sub

0 个答案:

没有答案