gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:06:54 25 4
gpt4 key购买 nike

我想创建一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com