自动递增 Excel OleDb 连接 Vb.net

Auto Increment Excel OleDb Connection Vb.net

我想在向 excel 添加新数据时自动递增 ID,但此代码不会自动递增,它只会递增 2,我不明白为什么请帮忙,谢谢

Dim Value As Integer
    cn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\Users\Barbatos\Desktop\Book3.xlsx " + ";Extended Properties=Excel 12.0;")
    cm = New OleDbCommand("SELECT MAX ([ID]) FROM [Sheet1$]", cn)
    cn.Open()
    Dim dr As OleDbDataReader = cm.ExecuteReader()
    If dr.HasRows Then
        dr.Read()
        Value = dr(0)
    Else
    End If
    dr.Close()
    Dim str As String
    Dim empid As Integer
    Dim newNumber As Integer
    str = "SELECT MAX([ID]) AS MAXIMUM FROM [Sheet1$]"
    Dim cmd2 As OleDbCommand = New OleDbCommand(str, cn)
    'Dim dr As OleDbDataReader
    dr = cmd2.ExecuteReader
    If dr.HasRows Then
        While dr.Read()
            If empid = IsDBNull(dr("MAXIMUM")) Then
                newNumber = CInt(Val(empid)) + 1
            End If
            If newNumber = 0 Then
                newNumber = 1
                empid = CStr(newNumber)
            ElseIf newNumber = 1 Then
                newNumber = newNumber + 1
                empid = CStr(newNumber)
            Else
                newNumber = newNumber + 1
                empid = CStr(newNumber)
            End If
        End While
    End If
    dr.Close()
    Me.Label2.Text = empid

已解决

If dr.HasRows Then
        dr.Read()
        If IsDBNull(dr("MAXIMUM")) Then
            empid = 1
        Else
            empid = CInt(dr("MAXIMUM")) + 1
        End If
    Else
        empid = 1
    End If

为了总结我的评论,我会这样做:

Dim nextId As Integer

Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Barbatos\Desktop\Book3.xlsx;Extended Properties=Excel 12.0;"),
      command As New OleDbCommand("SELECT MAX([ID]) FROM [Sheet1$]", connection)
    connection.Open()

    Dim currentId = command.ExecuteScalar()

    nextId = If(currentId Is DBNull.Value, 1, CInt(currentId) + 1)
End Using

或者,如果支持,则为:

Dim nextId As Integer

Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Barbatos\Desktop\Book3.xlsx;Extended Properties=Excel 12.0;"),
      command As New OleDbCommand("SELECT ISNULL(MAX([ID]), 0) FROM [Sheet1$]", connection)
    connection.Open()

    nextId = CInt(command.ExecuteScalar()) + 1
End Using