执行代码会产生运行时错误1004

时间:2016-03-17 19:14:38

标签: excel excel-vba vba

我准备了一个在演示文稿中工作正常但在将其放入最终工作表时会产生1004运行时错误的宏。

以下是我的代码:

Private Sub CommandButton3_Click()

'Declaring  the Variables
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim rng As Range
Dim startdate As Long
Dim enddate As Long
Dim tbl As ListObject
Dim fname As Variant

'Assigning the Variables
Set ws = Sheets("Reports")
Set ws3 = Sheets("Report Format")
Set rng = ws.Range("E7")
startdate = ws.Range("L10").Value
enddate = ws.Range("L12").Value

'Find the Worksheet against the Name selected in Drop Down List
For Each ws1 In Worksheets
If rng.Value = ws1.Name Then
Sheets(rng.Value).Activate
End If
Next

'Filter the data based on the Date Range Entered
Set ws2 = ActiveSheet
Set tbl = ws2.ListObjects(1)

Range(tbl & "[[Date]:[Cheque #]]").Select
Selection.AutoFilter Field:=1, Criteria1:=">=" & startdate,        Operator:=xlAnd, Criteria2:="<=" & enddate
Selection.Copy
ws2.Range("A10").Select

'Paste the Data in the Report Format
ws3.Activate
ws3.Range("B7").Select

Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

'Create the PDF of the Report
fname = Application.GetSaveAsFilename(InitialFileName:=rng.Value,     filefilter:="PDF files, *.pdf", Title:="Export to PDF")

If fname <> False Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname_,     quality:=xlQualityStandard, includedocproperties:=True, ignoreprintareas:=False, openafterpublish:=True
End If

'Clear the Report format Sheet for Future Printing
With ActiveSheet
.Rows(10 & ":" & .Rows.Count).Delete
End With

'Activate the Report Sheet
ws.Activate

'Unfilter all the Tables present in Workbook
Dim w As Long
For w = 1 To Worksheets.Count
With Worksheets(w)
**.UsedRange.Cells.EntireRow.Hidden = False**
If .AutoFilterMode Then .ShowAllData
End With
Next w

End Sub

错误出现在逗号中突出显示的行中。请仔细检查和调试。

1 个答案:

答案 0 :(得分:1)

您正在尝试将ListObject object连接到字符串中。您需要ListObject.Name属性。

Dim ws2 As Worksheet, tbl As ListObject

Set ws2 = ActiveSheet
Set tbl = ws2.ListObjects(1)
Debug.Print tbl.Name
Range(tbl.Name & "[[Date]:[Cheque '#]]").Select

请注意,'中的散列标记还有一个勾号(又名[Cheque '#]或Chr(39))。