列表对象所需的VBA对象

问题描述 投票:0回答:1

我这里有这段代码,总是在列表对象行给出错误代码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") & "\Desktop\Tryout\"

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
excel vba
1个回答
1
投票
为了使用可变的最佳实践是:
© www.soinside.com 2019 - 2024. All rights reserved.