I am working on a simple subroutine to pull values from the Primary Worksheet and to move those values to the additional sheets. When I run the VBA macro it never gets past the subroutine declaration, any suggestions would greatly be appreciated.
Option Explicit
Sub Macro2()
Dim rCell As Range, ws As Worksheet
Application.DisplayAlerts = False
With Sheets("Sheet1")
Sheets.Add().Name = "Temp"
.Range("D2", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True
For Each rCell In Sheets("Temp").Range("D2", Sheets("Temp").Range("B" & Rows.Count).End(xlUp))
If Not IsEmpty(rCell) Then
.Range("D2").AutoFilter field:=3, Criteria1:=rCell
If SheetExists(rCell.Text) Then
Set ws = Sheets(rCell.Text)
Else
Set ws = Worksheet.Add(After:=Worksheets(Worksheets.Count - 1))
ws.Name = rCell
End If
With .AutoFilter.Range
.Offset(1).Resize(.Rows.Count - 1).Copy ws.Range("A" & Rows.Count).End(xlUp)(2)
End With
End If
Next rCell
Sheets("Temp").Delete
.AutoFilterMode = False
End With
Application.DisplayAlerts = True
End Sub
added Function
Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
New error
extract range has a illegal or missing field name
#
.Range("D2", .Range("D"&Rows.Count).End(xlDown)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True
When I run that code, it says:
Compile Error:
Sub or Function not defined
and then highlights the SheetExists function. Either SheetExist is a function you forgot to include in your form, or it's a custom function that wasn't included in your example.
EDIT: Wow, there's a lot going on here.
If you step through the code after that, you'll also get a Run-time 1004 error ("Application-defined or object-defined error") here:
.Range("D2", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True
Try changing that to:
.Range("D2", .Range("D" & Rows.Count).End(xlDown)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True
From there, change this:
Set ws = Worksheets.Add(After:=Worksheets(Worksheets.Count - 1))
ws.Name = rCell
to this:
Worksheets.Add(After:=Worksheets(Worksheets.Count - 1)).Name = rCell
From there, though, I'm not sure what With .AutoFilter.Range is supposed to be doing, unless you meant With Sheets("Sheet1").AutoFilter.Range.
From a debugging standpoint, you really want to add On Error Goto ErrRoutine at the beginning of your code, then add this to the end of your routine:
Exit Sub
ErrRoutine:
MsgBox Err.Description
Resume
And put a breakpoint on MsgBox Err.Description to step back to the offending line.
Have you debugged to see exactly where it fails. For example you aren't trying to add a Sheet called Temp when one already exists. Debug and find exactly where it fails.
I
Related
I've recorded macros to autofilter and delete rows from a table. But this is not dynamic in the sense that if the filter criteria does not exist in a given table then the macro will break.
I am trying to create a code that will autofilter and delete the rows if the the criteria exists or otherwise do nothing. I am trying to follow this post, but I am missing something. Please help.
My code returns no errors, but also does not do anything. I added the message box to make sure that it was actually running.
Here is my code so far:
Sub autofilter()
Dim lo As ListObject
Set lo = Worksheets("BPL").ListObjects("Table1")
With Sheets(1)
If .AutoFilterMode = True And .FilterMode = True Then
If lo.Parent.autofilter.Filters(7).Criteria1 = "APGFORK" Then
'
lo.Range.autofilter Field:=7, Criteria1:="APGFORK"
Application.DisplayAlerts = False
lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
lo.autofilter.ShowAllData
'
End If
End If
End With
MsgBox ("Code Complete")
End Sub
Delete Filtered Rows in an Excel Table
Not entire rows!
Option Explicit
Sub DeleteFilteredRows()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim tbl As ListObject: Set tbl = wb.Worksheets("BPL").ListObjects("Table1")
Dim dvrg As Range ' Data Visible Range
With tbl
If .ShowAutoFilter Then
If .Autofilter.FilterMode Then .Autofilter.ShowAllData
End If
.Range.Autofilter 7, "APGFORK"
On Error Resume Next
Set dvrg = tbl.DataBodyRange.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
.Autofilter.ShowAllData
End With
Dim IsSuccess As Boolean
If Not dvrg Is Nothing Then
dvrg.Delete xlShiftUp
IsSuccess = True
End If
If IsSuccess Then
MsgBox "Data deleted.", vbInformation
Else
MsgBox "Nothing deleted.", vbExclamation
End If
End Sub
I don't know if it is a bug or a feature, but .AutoFilterMode seems to returns False all the time in Excel 2013 or later. All examples I see that use .AutoFilterMode are earlier than that.
I think the replacement is .ShowAutoFilter on the listobject. In your code, lo.ShowAutoFilter should return True or False depending on whether or not the autofilter is set or not.
But the rest of your code seems problematic too. The test
If lo.Parent.autofilter.Filters(7).Criteria1 = "APGFORK" Then
throws an error and removes the autofilter.
I Ended up taking a different approach:
Dim LastRowG As Long
LastRowG = Range("G" & Rows.Count).End(xlUp).Row
For i = 2 To LastRowG
If Range("G" & i).Value = "APGFORK" Then
lo.Range.autofilter Field:=7, Criteria1:="APGFORK"
Application.DisplayAlerts = False
lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
lo.autofilter.ShowAllData
Else
End If
Next i
This way if "APGFORK" does not exist in a data set, it will move on without an error code.
Try this code
Sub Test()
Call DelFilterParam("BPL", "Table1", 7, "APGFORK")
End Sub
Sub DelFilterParam(ByVal wsName As String, ByVal stTable As String, ByVal iField As Integer, ByVal vCriteria As Variant)
Dim x As Long, y As Long, z As Long
With ThisWorkbook.Worksheets(wsName)
With .ListObjects(stTable).DataBodyRange
x = .Rows.Count: y = .Columns.Count
.AutoFilter
.AutoFilter Field:=iField, Criteria1:=vCriteria
On Error Resume Next
z = .SpecialCells(xlCellTypeVisible).Count
On Error GoTo 0
If (x * y) > z And z <> 0 Then .EntireRow.Delete
.AutoFilter
End With
End With
End Sub
Hi guys I have this bunch of code:
For Each ws In ThisWorkbook.Sheets
If ws.Name = "Position calculation" Or ws.Name = "Strategies & weights" Then
Else
sheet_name = ws.Name
Sheets(sheet_name).Visible = True
ThisWorkbook.Worksheets(sheet_name).Activate
ws.Range("A2").Select
For Each c In Range("A2", "A1000")
If c.Value = "" Then
c.Activate
searched_cell = ActiveCell.Offset(-1, 0).Address
GoTo flag1
End If
Next c
Everytime when I try to run a code from a sheet called "Position calculation" I get the error saying
Run - time error '1004'
Activate method of Worksheet class failed
I cannot distinguish why the code is running from other sheets, but I have to run this script exactly from the page causing me this sort of error.
Thank you in advance for your help
I couldn't figure out why you receive the error that you complain about but it's certainly true that you wouldn't have the problem if you wouldn't ask for it (as has been pointed out to you by #Siddarth Rout in the comments above). In my analysis I found that your entire approach is a little cranked even if all Select and Activate statements are removed. Please consider the approach taken below.
Private Sub Try()
Dim Ws As Worksheet
Dim NextRow As Long
For Each Ws In ThisWorkbook.Worksheets
With Ws
If .Name <> "Position calculation" And .Name <> "Strategies & weights" Then
NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
If NextRow <= 1000 Then Exit For
End If
End With
Next Ws
NextRow = WorksheetFunction.Max(NextRow, 2)
MsgBox Ws.Name & vbCr & "cell " & Cells(NextRow, "A").Address(0, 0)
End Sub
This code will return the same result whichever sheet is active and regardless of whether a sheet is hidden or visible.
I'm trying to copy paste from an assigned variable worksheet to another.
I've been able to make do by recording but I would like to know how to do it manually.
This is the code I made:
Sub Parse_Reportable()
Dim ws As Worksheet
Sheets.Add.Name = "Copy to Reportable or TAK"
Set ws = Sheets("Copy to Reportable or TAK")
Sheets("sheet1").Select
Range("H3", Cells.Columns(8).End(x1Down)).Copy
ws.Cells(2, 2).Paste
End Sub
Running it creates the worksheet but gives me an
object defined error
in the copy code.
Cells.Columns(8).End(x1Down) will give you the error. It also has a typo. x1Down
Instead of using xlDown, use xlUp to find the last row using THIS and then construct your range to copy.
Is this what you are trying? (Untested)
Option Explicit
Sub Parse_Reportable()
Dim rngToCopy
Dim ws As Worksheet
Dim lRow As Long
Sheets.Add.Name = "Copy to Reportable or TAK"
Set ws = Sheets("Copy to Reportable or TAK")
With Sheets("sheet1")
lRow = .Range("H" & .Rows.Count).End(xlUp).Row
Set rngToCopy = .Range("H3:H" & lRow)
End With
rngToCopy.Copy ws.Cells(2, 2)
End Sub
Note: You may also want to delete the sheet "Copy to Reportable or TAK" if it already exists before naming the new sheet with that name else you will again get an error.
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Copy to Reportable or TAK").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Sheets.Add.Name = "Copy to Reportable or TAK"
I have a code to filter data and copy to new worksheet. I have an issue where if the sheet being created already exists then it will jump to error handling and stop not continue with remaining 'next'. If i move the 'Next' after the error handling it will only loop if there is and error. Is there a way I can have both?
Sub SortDataAll()
' Sort Data All
If (Workbooks("Fakturagrunnlag All_1.xlsm").Sheets("All Focal Point Data").AutoFilterMode And Workbooks("Fakturagrunnlag All_1.xlsm").Sheets("All Focal Point Data").FilterMode) _
Or Workbooks("Fakturagrunnlag All_1.xlsm").Sheets("All Focal Point Data").FilterMode Then
Workbooks("Fakturagrunnlag All_1.xlsm").Sheets("All Focal Point Data").ShowAllData
End If
'~~> Set filter of main data
Dim rRange As Range
Dim rCell As Range
Set rRange = Worksheets("Front Page").Range("A7:A21")
For Each rCell In rRange
MsgBox "Setting filter for " & rCell
Dim rList As String
rList = rCell & "List"
MsgBox "The list for filter is" & rList
' can remove after
Worksheets("All Focal Point Data").Activate
Dim v As Variant
v = Application.WorksheetFunction.Transpose(Range(rList).Value)
Range("A:BC").AutoFilter Field:=54, Criteria1:=v, Operator:=xlFilterValues
Selection.AutoFilter Field:=54, Criteria1:=v, Operator:=xlFilterValues
MsgBox "Check data is filtered"
'~~> Create new sheet and paste data
On Error Resume Next
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = rCell
End With
If Err Then GoTo ErrorJump
Err.clear
Worksheets("All Focal Point Data").Range("A1:BC5000").Copy Worksheets(rCell).Range("A1").Paste
Columns("BB:BB").Delete Shift:=xlToLeft
Next rCell
Exit Sub
ErrorJump:
MsgBox "Sheet already exists":
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
'Worksheets("Front Page").Activate
'Range("A1").Select
Next rCell
End Sub
I've used a method where you simply try to use the worksheet and let error control create the worksheet if an error is thrown.
In this, if the abc worksheet exists, it is used. If it doesn't exist, it is created then used.
sub testws()
dim wsn as string
wsn = "abc"
on error goto make_ws
with worksheets(wsn)
on error goto 0
...
end with
exit sub
make_ws:
with worksheets.add
.name = wsn
end with
resume
end sub
The following loop is working like a charm on one data set but on another data set with the same fields it is not working and giving me an error. I am at my wits end. Any debugging guidance would be greatly appreciated.
For Each Itm In Array("SCL_FL", "FSL_SCL_FX")
Workbooks(Original_Name).Sheets("Sheet1").Select
Selection.Copy
Workbooks.Add
ActiveSheet.Name = Itm
Sheets(Itm).Paste
If Itm = "SCL_FL" Then
Worksheets(Itm).UsedRange.AutoFilter Field:=3, Criteria1:="=SCL_FL"
Else
Worksheets(Itm).UsedRange.AutoFilter Field:=3, Criteria1:=Array("FSL", "SCL_FX"), Operator:=xlFilterValues
End If
Next Itm
I get the error "autofilter method of range class failed"
I get the same error when I do
Worksheets(Itm).UsedRange.AutoFilter Field:=3, Criteria1:="SCL_FL", Operator:=xlFilterValues
Why is this line working on one data but not working on another data? Both data are actually the same. Just copied and pasted into different files with different file names.
You are getting that error because you are adding a workbook after the Sheet1.Copy command. The copy command already creates a new workbook. If you again add a new workbook after that, naturally the usedrange will give you $A$1 as mentioned in the comments above.
Change your code to this and it will work.
Sub Run1Nov24()
'
'~~>Rest of your code
'
Dim itm
Dim wb As Workbook
Dim ws As Worksheet
For Each itm In Array("SCL_FL", "FSL_SCL_FX")
Set wb = Workbooks.Add
Workbooks(Original_Name).Sheets("Sheet1").Copy Before:=wb.Sheets(1)
Set ws = wb.Sheets(1)
With ws
.AutoFilterMode = False
.Name = itm
If itm = "SCL_FL" Then
.UsedRange.AutoFilter Field:=3, Criteria1:="=SCL_FL"
Else
.UsedRange.AutoFilter Field:=3, Criteria1:=Array("FSL", "SCL_FX"), Operator:=xlFilterValues
End If
End With
Next itm
'
'~~>Rest of your code
'
End Sub