列表对象所需的 VBA 对象

  • 本文关键字:对象 VBA 列表 excel vba
  • 更新时间 :
  • 英文 :


我这里有这个代码,它一直给出一个错误代码,在列表对象行显示Object required

Dim table As ListObject
Set table = wks.ListObjects("TableName")
Dim newRow As ListRow
Set newRow = table.ListRows.Add

下面是完整的代码,我不知道缺少什么对象,谁能建议我? 非常感谢!

Sub GenerateData()
Dim sheet As Worksheet
Set sheet = CreateOutputSheet(ActiveWorkbook)
Dim basePath As String
basePath = Environ$("USERPROFILE") & "DesktopTryout"
Dim baseFolder As Scripting.Folder
With New Scripting.FileSystemObject
Set baseFolder = .GetFolder(basePath)
End With
Dim table As ListObject
Set table = wks.ListObjects("TableName")
Dim newRow As ListRow
Set newRow = table.ListRows.Add
Dim source As Range
Set source = wksData.Range("A:A")
PopulateIfFound source, "  testtest         : ", newRow, 1
PopulateIfFound source, "  testflyy         : ", newRow, 2
PopulateIfFound source, "  testflyy         : ", newRow, 3
PopulateIfFound source, "  Started at: ", newRow, 4
If Not PopulateIfFound(source, "SmartABC ", newRow, 9) Then
PopulateIfFound source, "smart_mfh revision", newRow, 9
End If
If Not PopulateIfFound(source, "ERROR: ABC ", newRow, 10, True) Then
PopulateIfFound source, "ERROR: DEF ", newRow, 10
End If
End Sub
Private Sub AddColumnHeaders(ByVal sheet As Worksheet)
sheet.Range("A1:K1") = Array( _
"Test", "Temp", "Type", "StartDate", _
"FileName", "No", "EndDate", "Month", _
"Smart", "Errors", "ErrorCellAddress")
End Sub
Private Function CreateOutputSheet(ByVal book As Workbook) As Worksheet
Dim sheet As Worksheet
Set sheet = book.Worksheets.Add(After:=book.Worksheets(book.Worksheets.Count))
AddColumnHeaders sheet
Set CreateOutputSheet = sheet
End Function
Private Function PopulateIfFound(ByVal source As Range, ByVal value As String, ByVal row As ListRow, ByVal writeToColumn As Long, Optional ByVal writeAddressToNextColumn As Boolean = False) As Boolean
Dim result As Range
Set result = source.Find(value, LookIn:=xlValues)
If Not result Is Nothing Then
Dim cell As Range
Set cell = row.Range.Cells(ColumnIndex:=writeToColumn)
cell.value = result.value
If writeAddressToNextColumn Then
cell.Offset(ColumnOffset:=1).value = result.Address
End If
PopulateIfFound = True
End If
End Function

您正在使用wks变量,该变量未在任何地方分配。

为了使用变量,最佳实践是:

  1. 使用关键字声明Dim

  2. =运算符分配它(很明显(

因此,例如,对于Worksheet对象,它将是:

Dim wks As Worksheet
' reference types ned Set keyword when assigning
Set wks = Worksheets("Sheet1") ' just example

最新更新