原始错误:
我有一个VBA脚本,可以过滤日期列中的日期范围,过滤器功能之前有效,但经过一些修改后会提示错误消息
对象变量或未设置块变量
在第AparSheet.AutoFilterMode = False
行
我不确定为什么会出现此错误,我搜索了解决方案,但我没有任何select
代码,而是设置了工作表名称而不是active
。
新错误:
我的代码现在正在运行但运行不正常,它会覆盖以前的记录集,我认为这是由于我的代码中的一些逻辑,我已经为我的代码添加了注释。
我的相关代码块在这里,其他信息将根据要求更新:
Set wkbCrntWorkBook = ActiveWorkbook
'// Set here Workbook(Sheets) names
Set wSheet2 = wkbCrntWorkBook.Worksheets("Sheet2")
Set wSheet3 = wkbCrntWorkBook.Worksheets("Sheet1")
'wSLastPasteRow = 2
'extract data from another excel file
With Application.FileDialog(msoFileDialogOpen)
.Filters.Clear
.Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xls"
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
'Prompts user to choose which Worksheet they want to copy from
MSG1 = MsgBox("Do you wish to copy from 'Overall details' ?", vbYesNo, "Name of Worksheet")
If MSG1 = vbYes Then
worksheetName = "Overall details"
Else
Default = "Sheet"
worksheetName = Application.InputBox("Enter the name of Worksheet (Case-sensitive)", Default, Default)
'End of first If statement
End If
Set wkbSourceBook = Workbooks.Open(.SelectedItems(1))
Set WintelSheet = wkbSourceBook.Sheets(worksheetName)
With WintelSheet
'// Here lets Find the last row of data
wSlastRow = .Range("B" & .Rows.Count).End(xlUp).Row
'// Now Loop through each row
For X = 2 To wSlastRow
If Not IsError(.Range("AI" & X).Value) Then
If IsDate(.Range("AI" & X)) Then
'//Calculate the last day of the month for dates in Column W (dtStart) and first day of the next current month (dtFinal)
dtStart = DateSerial(Year(.Range("AI" & X)), Month(.Range("AI" & X)) + 1, 1)
dtFinal = DateSerial(Year(Now), Month(Now) + 1, 1)
With AparSheet
.AutoFilterMode = False
.Range("L:L").AutoFilter 1, ">=" & dtStart, xlAnd, "<" & dtFinal
NumberOfPasteRows = .Rows(.Range("J:J").Rows.Count).End(xlUp).Row
'//Copy from second row to the last row in AparSheet
For Y = 2 To NumberOfPasteRows
'//Copy the whole data from second rows to the last rows over "GeneratedSheet", I feel this copy method can be still improved
Union(.Range("J" & Y), .Range("J" & NumberOfPasteRows)).EntireRow.Copy Destination:=GeneratedSheet.Rows(wSLastPasteRow & ":" & NumberOfPasteRows)
'//Copy the data in Column B WintelSheet to the Column B at number of paste rows times, I'm thinking to use array for this line, is it doable?
WintelSheet.Range("B" & X).Copy Destination:=Union(GeneratedSheet.Range("B" & wSLastPasteRow), GeneratedSheet.Range("B" & NumberOfPasteRows))
wSLastPasteRow = wSLastPasteRow + NumberOfPasteRows
Next wSLastPasteRow
End With
End If
End If
'If (AparSheet.AutoFilterMode And AparSheet.FilterMode) Or AparSheet.FilterMode Then
'AparSheet.ShowAllData
'End If
Next X
End With
wkbSourceBook.Close False
End If
End With