我正在尝试创建一个sub,它将在变量中存储工作表中的各种值,然后将变量复制到listobject(table)中空行的相应列中。我继续收到以下错误:
“运行时错误'91': 对象变量或With块变量未设置“
我尝试了很多变化,但不断出现错误,有时甚至是不同的错误。任何建议都非常感谢。这是代码
Sub RecordData()
Dim strName1 As String, strName2 As String
Dim dTimeStamp As Date
Dim sItem1 As Single, sItem2 As Single, sItem3 As Single
Dim sItem4 As Single
Dim ws_1 As Worksheet, ws_2 As Worksheet
Set ws_1 = Sheets("Data")
Set ws_2 = Sheets("Output")
strName1 = ws_1.Range("D1").MergeArea.Cells(1, 1).Value
strName1 = Left(strName1, Len(strName1) - 6)
strName2 = ws_1.Range("B17")
dTimestamp = Now
sItem1 = ws_1.Range("D3")
sItem2 = ws_1.Range("E3")
sItem3 = ws_1.Range("F3")
sItem4 = ws_1.Range("N3")
Dim loTable As ListObject
Set loTable = ws_2.ListObjects("CurrentMkts")
Dim iLastRow As Integer
iLastRow = loTable.Range.Rows.Count
If iLastRow = 2 Then
Dim iTempRow As Integer
iTempRow = iLastRow - 1
loTable.DataBodyRange.Cells(iTempRow, 1).Value = dTimeStamp
loTable.DataBodyRange.Cells(iTempRow, 2).Value = sItem1
loTable.DataBodyRange.Cells(iTempRow, 3).Value = sItem2
loTable.DataBodyRange.Cells(iTempRow, 4).Value = sItem3
loTable.DataBodyRange.Cells(iTempRow, 6).Value = sItem4
loTable.ListRows.Add
Else
iTempRow = iLastRow
loTable.DataBodyRange.Cells(iTempRow, 1).Value = dTimeStamp
loTable.DataBodyRange.Cells(iTempRow, 2).Value = sItem1
loTable.DataBodyRange.Cells(iTempRow, 3).Value = sItem2
loTable.DataBodyRange.Cells(iTempRow, 4).Value = sItem3
loTable.DataBodyRange.Cells(iTempRow, 6).Value = sItem4
loTable.ListRows.Add
End If
End Sub
感谢您的帮助。
答案 0 :(得分:0)
由于看似非感性的方式导致错误发生空白ListObjects在Excel中处理。
基本上,在这种情况下,由于ListObject中没有数据,Excel将DataBodyRange
属性视为不存在,因此当您尝试设置DataBodyRange
的单元格的值时代码错误。
要解决此问题,请在loTable.ListRows.Add
块的第一部分中将IF
移至设置单元格值之前的行。
IF块的第二部分不应该将loTable.ListRows.Add移到顶部,因为实际的数据行将会出现。