Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Excel VBA在Excel记录集中插入行_Excel_Vba - Fatal编程技术网

通过Excel VBA在Excel记录集中插入行

通过Excel VBA在Excel记录集中插入行,excel,vba,Excel,Vba,我试图在记录集的最后一行插入一些值,在本例中,该记录集是用作数据库的Excel文件。下面的代码用于将文本框的值插入excel记录集的最后一行。但是,它没有创建插入值的新表行 Sub CreaterRow() Dim strFile As String Dim strConnect As String Dim strSQL As String Dim lngCount As Long Dim cnn As New ADODB.Connection D

我试图在记录集的最后一行插入一些值,在本例中,该记录集是用作数据库的Excel文件。下面的代码用于将文本框的值插入excel记录集的最后一行。但是,它没有创建插入值的新表行

Sub CreaterRow()
    Dim strFile As String
    Dim strConnect As String
    Dim strSQL As String
    Dim lngCount As Long
    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    strFile = "C:\Excel\Test.xlsx"
    strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile & _
    ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    cnn.Open ConnectionString:=strConnect
    strSQL = "SELECT [ID] FROM [Sheet1$]"
    rst.Open Source:=strSQL, ActiveConnection:=cnn, CursorType:=adOpenForwardOnly, Options:=adCmdText

    With rst
        .AddNew
           .Fields("ID").Value = tbx_ID.Value 'Inserting this in the recordset did not create a new row
         .Update
    End with 

    rst.Close
    cnn.Close
End Sub

表如何自动创建一个新行,其中包含插入到最后一行中的值?多谢各位

这对我很有效。您需要具有正确的光标和锁定类型

Sub CreaterRow()
    Dim strFile As String
    Dim strConnect As String
    Dim strSQL As String
    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset

    strFile = ThisWorkbook.Path & "\Data.xlsx"

    strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & strFile & _
                """;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    cnn.Open ConnectionString:=strConnect
    strSQL = "SELECT [ID] FROM [Sheet1$]"

    rst.Open strSQL, cnn, adOpenKeyset, adLockOptimistic

    With rst
        .AddNew
        .Fields("ID").Value = "ID00020"
        .Update
    End With

    rst.Close
    cnn.Close
End Sub
编辑:如果您正在查询表/列表对象中的数据,则附加记录不会调整列表的大小以包括添加的记录。见:


EDIT2:如果使用命名范围而不是ListObject,则可以按名称而不是使用工作表名称查询,插入新行时,范围将进行调整。

您不需要在记录集上调用Update谢谢您指出这一点。我无法粘贴“.Update”我的问题保持不变。您没有收到任何错误吗?没有,我没有收到任何错误。它可以正常工作,但仍然没有创建表行。您的结果是否创建了新表行?是-添加到现有数据的末尾。对我来说,该值已插入并附加到数据的末尾,但该表未创建新行。我将尝试创建一个新的表,如果这将工作。谢谢。我非常感谢你提供的见解。如果你可以修改你的答案,也将反映在链接中的信息,那么我会检查你的答案。总之,在这种情况下不可能添加表行,对吗?