我这里有这段代码,该代码始终在列表对象行给出错误代码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
答案 0 :(得分:1)
您正在使用wks
变量,该变量未分配到任何地方。
为了使用可变的最佳实践是:
使用Dim
关键字进行声明
使用=
运算符进行分配(非常明显)
例如,对于Worksheet
对象,它将是:
Dim wks As Worksheet
' reference types ned Set keyword when assigning
Set wks = Worksheets("Sheet1") ' just example