【发布时间】:2019-03-16 03:52:36
【问题描述】:
我有一些 VBA 代码,我在另一个工作簿中使用这些代码将表调整为 1 行并删除数据表的内容以初始化工作簿。然后会打开一个文件提示,要求用户选择适当的文件进行处理。出于某种原因,我得到了一个
“运行时错误'91':对象变量或未设置块变量”
代码是从其他工作簿复制和粘贴的,我已经调整了变量、工作簿、工作表和表名的名称。
工作簿名为“IMD Processing.xlsm”,包含 2 张标题为“IMD”和“Raw”的工作表。 “Raw”表有一个名为“tbl_raw”的表,“IMD”表有一个名为“tbl_imd”的表。
任何指导将不胜感激。
Option Explicit
Sub IMDAutomation()
Dim fileName As String 'Filename string
Dim wb_macro As Workbook 'Macro workbook
Dim ws_macro_imd As Worksheet 'Macro worksheet
Dim ws_macro_raw As Worksheet 'Macro raw worksheet
Dim wb_imd As Workbook 'IMD Workbook for processing
Dim ws_imd As Worksheet 'IMD Worksheet for processing
Dim objTable As ListObject 'Table of raw data
Dim tbl_raw As ListObject 'Raw table in macro workbook
Dim tbl_imd As ListObject 'IMD table in macro workbook
Dim vals As Variant 'Array to store values
Dim lrow As Long 'Variable used to determine number of rows in data table
Set wb_macro = ThisWorkbook
Set ws_macro_imd = Sheets("IMD")
Set ws_macro_raw = Sheets("Raw")
'============ Initialize macro workbook - clearing data ============'
'Clear the raw data in the macro workbook
Set tbl_raw = ws_macro_raw.ListObjects("tbl_raw")
With tbl_raw.DataBodyRange
If .Rows.Count > 1 Then
.Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
End If
End With
tbl_raw.DataBodyRange.Rows(1).ClearContents
'Clear the IMD data in the macro workbook
Set tbl_imd = ws_macro_imd.ListObjects("tbl_imd")
With tbl_imd.DataBodyRange
If .Rows.Count > 1 Then
.Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
End If
End With
'============ Locate Raw Data File ============'
'Open file dialog to locate the Workforce Review raw data workbook exported from system
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select the IMD file"
.Filters.Clear
.Filters.Add "Custom Excel Files", "*.xlsx, *xls, *csv"
.Show
fileName = .SelectedItems.Item(1)
End With
If InStr(fileName, ".xlsx") = 0 Then
Exit Sub
End If
Workbooks.Open fileName
'Set the Workforce Review raw workbook
Set wb_imd = ActiveWorkbook
'Set the worksheet
Set ws_imd = wb_imd.ActiveSheet
lrow = ws_imd.Cells(ws_imd.Rows.Count, 2).End(xlUp).Row
vals = ws_imd.Range("A2:CU" & lrow)
Application.CutCopyMode = False
Application.CutCopyMode = True
End Sub
UDPATE 解决方案
感谢@Variatus 的解决方案。
我的表中没有数据行,所以我创建了一个,现在它可以工作了。
这应该可以处理表中没有行的情况。 If tbl_raw.DataBodyRange Is Nothing Then InsertRowRange Else (Code to clear the table)
【问题讨论】:
-
你在哪一行得到这个错误?
-
当我使用 step-into 时,它会在黄色箭头位于
If .Rows.Count > 1 Then时发生。一旦我再次进入,错误就会跳闸。我不确定这是否意味着它在该行或下一行。 -
DataBodyRange 不存在。必须至少有一排。我相信您可以使用
If Tbl_raw.DataBodyRange Is Nothing对其进行测试。相反,表的InsertRowRange仅在 DataBodyRange 为 Nothing 时才存在。 -
啊,我以为我有一行数据!这确实解释了。所以你会说一个解决方案是:
If tbl_raw.DataBodyRange Is Nothing Then InsertRowRange Else (Code to clear the table)?另外,我可以使用“什么都没有”吗?还是您说的是逻辑? -
Is Nothing是合法的。