vba - 用于向表添加新行和数据的函数或子函数

标签 vba excel

我想创建一个 Sub,它基本上允许我定位具有特定名称的 Excel 表,然后在底部插入一个新行,同时向该行添加数据。然后退出子程序。如果表只有一行且没有数据,则将数据添加到该行,然后退出子程序。

我该怎么做?

我在想这样的伪代码:

Public Sub addDataToTable(ByVal strTableName as string, ByVal strData as string, ByVal col as integer)

ActiveSheet.Table(strTableName).Select
If strTableName.Rows.Count = 1 Then
    strTableName(row, col).Value = strData
Else
    strTable(lastRow, col).Value = strData
End if

End Sub

这可能根本不是有效的代码,但它至少应该解释我所追求的内容!

最佳答案

我需要同样的解决方案,但如果您使用 native ListObject.Add()方法,这样您就可以避免与表格正下方的任何数据发生冲突的风险。下面的例程检查表的最后一行,如果该行为空,则添加数据;否则它会在表末尾添加一个新行:

Sub AddDataRow(tableName As String, values() As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = ActiveWorkbook.Worksheets("Sheet1")
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        For col = 1 To lastRow.Columns.Count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                table.ListRows.Add
                Exit For
            End If
        Next col
    Else
        table.ListRows.Add
    End If

    'Iterate through the last row and populate it with the entries from values()
    Set lastRow = table.ListRows(table.ListRows.Count).Range
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
    Next col
End Sub

要调用该函数,请传递表名称和一组值,每列一个值。您可以从功能区的“设计”选项卡获取/设置表的名称,至少在 Excel 2013 中: enter image description here

三列表格的示例代码:

Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x

关于vba - 用于向表添加新行和数据的函数或子函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8295276/

相关文章:

excel - VBA:循环遍历Excel过滤器中的条件?

Excel VBA 代码强制指定缩放级别

vba - 将浏览器中的 URL 复制到 Excel 中

vb.net - 出现错误时,转到下一个所需的操作,而不是下一行

python - Pandas:导入带有多个工作表的 xlsx,将列添加到每个 df 及其所属工作表的名称,连接具有相同列数的 df

excel - 如何按功能选择单元格

excel - 如何对范围内的一个单元格值进行编号,然后在单元格值发生变化时重新开始编号

ms-access - 在 FileDialog 中使用 CurrentProject.Path 作为默认文件夹时出现 "Path does not exist"错误

excel - 基于 VBA Excel 中列标题的动态列选择

excel - 在 Excel 中将 VBA 代码另存为单独的文件