Excel VBA通​​过清除表来初始化工作簿

时间:2019-03-15 18:28:29

标签: excel vba

我有一些VBA代码,我在另一个工作簿中使用该代码将表的大小调整为1行,并删除数据表的内容以初始化工作簿。然后打开一个文件提示,要求用户选择适当的文件进行处理。由于某种原因,我得到了

  

“运行时错误'91':对象变量或未设置块变量”

该代码是从另一个工作簿复制并粘贴的,我已经调整了变量,工作簿,工作表和表名的名称。

工作簿称为“ IMD Processing.xlsm”,带有两张名为“ IMD”和“ 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)

1 个答案:

答案 0 :(得分:1)

在新工作簿中,Set tbl_raw = ws_macro_raw.ListObjects("tbl_raw")正在搜索的对象可能不存在,因此通过With tbl_raw进行引用会返回此错误