我正在尝试将一组过滤后的数据从一张纸复制到另一张纸的底部。我的代码工作得很好,除了第一次打开文件我得到了:
运行时错误1004
如果我退出调试器并重新运行宏,它的工作效果很好 这是我的代码:注意问题发生的地方。
Sub MoveData_Click()
'Select the filtered alarm data and paste on the master spreadsheet
Sheets("DailyGen").Select
ActiveSheet.UsedRange.Offset(5, 0).SpecialCells _
(xlCellTypeVisible).Copy
Sheets("2015 Master").Select
If ActiveWorkbook.ActiveSheet.FilterMode _
Or ActiveWorkbook.ActiveSheet.AutoFilterMode Then
ActiveWorkbook.ActiveSheet.ShowAllData
End If
Range("C4").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, -2).Range("A1").Select
ActiveSheet.Paste '~~> THIS IS WHERE IT ERRORS
'Sort newest to oldest in the date column
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Add _
Key:=Range("Table44[[#All],[Active Time]]"), _
SortOn:=xlSortOnValues,
Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
答案 0 :(得分:0)
当您ShowAllData
(与“过滤器”部分中的Data->Clear
相同)时,您正在清空剪贴板并告知Excel忘记复制的Range
。在VBA之外做,以确认是否需要。 Excel喜欢在编辑单元格时清空剪贴板或执行除选择之外的其他操作。
要解决此问题,请在Copy
之后执行ShowAllData
。在您的情况下,您必须来回Select
Worksheet
。
您通常应该努力避免对您的VBA使用Select
和Activate
。 See this post for details.
以下是进行更改的最终代码:
Sub MoveData_Click()
'Select the filtered alarm data and paste on the master spreadsheet
Sheets("2015 Master").Select
If ActiveWorkbook.ActiveSheet.FilterMode Or ActiveWorkbook.ActiveSheet.AutoFilterMode Then
ActiveWorkbook.ActiveSheet.ShowAllData
End If
Sheets("DailyGen").Select
ActiveSheet.UsedRange.Offset(5, 0).SpecialCells _
(xlCellTypeVisible).Copy
Sheets("2015 Master").Select
Range("C4").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, -2).Range("A1").Select
ActiveSheet.Paste
'Sort newest to oldest in the date column
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Add _
Key:=Range("Table44[[#All],[Active Time]]"), SortOn:=xlSortOnValues, Order _
:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub