Cannot Bypass Error 619 "Control not found" - scripting

I have the following code and it appears to always produce an error 619 "Control not found" at line session.findById("wnd[1]/tbar[0]/btn[0]").press, even though I have entered Application.DisplayAlerts = False and I've taken extra precaution to bypass the error. I have attempted using On Error GoTo, On Error Resume Next, and even If IsError(), but none of that seems to be working.
'Insert Sum of Amts and list as Balance on Summary tab
Sheets(2).Select
LastRow = ActiveSheet.UsedRange.Rows.Count
Range("D" & LastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R2C4:R" & LastRow & "C4)"
Columns("D:D").Select
Selection.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(#_)"
Sheets(1).Select
Range("C7").Select
ActiveCell.FormulaR1C1 = "=Statement!R" & LastRow + 1 & "C4"
'Insert V-lookup for open items
Sheets(2).Select
Range("G2").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(RC[-1]=""R"",RC[-1]=""A""),""-"",IF(IFERROR(VLOOKUP(RC[-5],'FBL1N Scheduled'!C1:C2,2,0), ""-"")>TODAY(),IFERROR(VLOOKUP(RC[-5],'FBL1N Scheduled'!C1:C2,2,0), ""-""),IF(IFERROR(VLOOKUP(RC[-5],'FBL1N Scheduled'!C1:C2,2,0), ""-"")<=DATE(YEAR(TODAY()),MONTH(TODAY()),15),IF(TODAY()<=DATE(YEAR(TODAY()),MONTH(TODAY()),15),DATE(YEAR(TODAY()),MONTH(TODAY()),15),EOMONTH(TODAY(),0)))))"
Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G" & LastRow), Type:=xlFillDefault
Range("G2:G" & LastRow).Select
Selection.NumberFormat = "mm/dd/yyyy;#"
'Insert V-lookup for cleared items
Range("H2").Select
ActiveCell.FormulaR1C1 = _
"=IF(RC[-1]<>""-"",""-"",IFERROR(VLOOKUP(RC[-6],'FBL1N Paid'!C1:C2,2,0),""-""))"
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H" & LastRow), Type:=xlFillDefault
Range("H2:H" & LastRow).Select
Selection.NumberFormat = "mm/dd/yyyy;#"
'Autofit and filter
Cells.Select
Cells.EntireColumn.AutoFit
Application.CutCopyMode = False
Selection.AutoFilter
'Copy values for Vim
LastRow = ActiveSheet.UsedRange.Rows.Count
ActiveSheet.Range("$A$1:$K$" & LastRow).AutoFilter Field:=7, Criteria1:="-"
ActiveSheet.Range("$A$1:$K$" & LastRow).AutoFilter Field:=8, Criteria1:="-"
'Insert DPN for processing/obsolete invoices
With Worksheets("Statement").AutoFilter.Range
Range("E" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-3],'VIM Export'!C1:C5,3,0),"""")"
'Copy down in only visible
With ActiveSheet.UsedRange
.Resize(.Rows.Count - 1).Offset(1).Columns("E"). _
SpecialCells(xlCellTypeVisible).FillDown
End With
'Select Reference #
With Worksheets("Statement").AutoFilter.Range
Range("B" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With
'If none are left processing, skip VIM
If ActiveCell.Value = "" Then GoTo Valuations:
'Copy all invoice numbers not posted
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
'Switch to Summary page to pull vendor data in VIM search
Sheets(1).Select
'Execute in SAP
If Not IsObject(SAPApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SAPApp.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject SAPApp, "on"
End If
'Open Vim and apply parameters (inserting Doc Numbers)
session.findById("wnd[0]/tbar[0]/btn[12]").press
session.findById("wnd[0]/tbar[0]/btn[12]").press
't-code entered in bar
session.findById("wnd[0]/tbar[0]/okcd").Text = "/n/opt/vim_analytics"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/btn%_S_XBLNR_%_APP_%-VALU_PUSH").press
session.findById("wnd[1]/tbar[0]/btn[24]").press
session.findById("wnd[1]").sendVKey 8
session.findById("wnd[0]/usr/btn%_S_LIFNR_%_APP_%-VALU_PUSH").press
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = Cells(3, 1).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").Text = Cells(4, 1).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,2]").Text = Cells(5, 1).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,3]").Text = Cells(3, 3).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,4]").Text = Cells(4, 3).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,5]").Text = Cells(5, 3).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").SetFocus
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").caretPosition = 7
session.findById("wnd[1]").sendVKey 8
session.findById("wnd[0]").sendVKey 8
On Error Resume Next
session.findById("wnd[1]/tbar[0]/btn[0]").press
If Err.Number = 0 Then
'Export to Excel (Existing XXL Format)
session.findById("wnd[0]/usr/cntlCL_GRID/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlCL_GRID/shellcont/shell").selectContextMenuItem "&XXL"
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Select Export and Paste into Workbook
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Cut
Windows("Updated Auto Recon.xlsm").Activate
Sheets(5).Select
Range("A1").Select
ActiveSheet.Paste
'Clear Formatting
ThisWorkbook.ActiveSheet.Cells.ClearFormats
'Close temporary export sheet
Windows("Worksheet in Basis (1)").Activate
ActiveWindow.Close
If Not IsObject(SAPApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SAPApp.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject SAPApp, "on"
End If
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Formatting VIM Export
''Moves columns to the appropriate postions in the worksheet
''Move Reference to Column A; Move CoCode to Column B; Move Doc. ID to Column C; Move Document Status to Column D
Range("A1").End(xlToRight).Select
LastColumn = ActiveCell.Column
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "CoCd" Then
ActiveCell.Value = "CoCode"
ElseIf ActiveCell.Value = "Company Code" Then
ActiveCell.Value = "CoCode"
ElseIf ActiveCell.Value = "DocumentStatus" Then
ActiveCell.Value = "Document Status"
ElseIf ActiveCell.Value = "DOC Status" Then
ActiveCell.Value = "Document Status"
ElseIf ActiveCell.Value = "DOC status" Then
ActiveCell.Value = "Document Status"
ElseIf ActiveCell.Value = "Document Id" Then
ActiveCell.Value = "Doc. Id"
ElseIf ActiveCell.Value = "Vendor Nam" Then
ActiveCell.Value = "Vendor Name"
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Reference" Then
If ActiveCell.Column <> 1 Then
Columns(i).Select
Selection.Cut
Columns("A").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "CoCode" Then
If ActiveCell.Column <> 2 Then
Columns(i).Select
Selection.Cut
Columns("B").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Doc. Id" Then
If ActiveCell.Column <> 3 Then
Columns(i).Select
Selection.Cut
Columns("C").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Document Status" Then
If ActiveCell.Column <> 4 Then
Columns(i).Select
Selection.Cut
Columns("D").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Vendor" Then
If ActiveCell.Column <> 5 Then
Columns(i).Select
Selection.Cut
Columns("E").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Vendor Name" Then
If ActiveCell.Column <> 6 Then
Columns(i).Select
Selection.Cut
Columns("F").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
'Remove Confirmed Duplicate Status
i = Application.WorksheetFunction.CountIf(Columns("D:D"), "Confirmed Duplicate")
If i > 0 Then
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
Selection.AutoFilter
ActiveSheet.Range(Cells(1, 1), Cells(LastRow, LastColumn)).AutoFilter Field:=4, Criteria1:="Confirmed Duplicate", _
Operator:=xlAnd
Rows("2:" & LastRow).SpecialCells(xlCellTypeVisible).Select
Selection.Delete Shift:=xlToLeft
ActiveSheet.ShowAllData
Else
End If
'Remove Cancelled Status
i = Application.WorksheetFunction.CountIf(Columns("D:D"), "Cancelled")
If i > 0 Then
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
Selection.AutoFilter
ActiveSheet.Range(Cells(1, 1), Cells(LastRow, LastColumn)).AutoFilter Field:=4, Criteria1:="Cancelled", _
Operator:=xlAnd
Rows("2:" & LastRow).SpecialCells(xlCellTypeVisible).Select
Selection.Delete Shift:=xlToLeft
ActiveSheet.ShowAllData
Else
End If
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'Force Doc Id to convert to number
Range("C:C").Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'Force Vendor # to convert to number
Range("E:E").Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
'Sorts Reference number by most recent document status
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
Range("A2").Activate
ActiveWorkbook.Worksheets("VIM Export").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("VIM Export").Sort.SortFields.Add Key:=Range( _
"C2:C" & LastRow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("VIM Export").Sort.SortFields.Add Key:=Range( _
"A2:A" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("VIM Export").Sort
.SetRange Range(Cells(1, 1), Cells(LastRow, LastColumn))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A2").Select
Else
Err.Clear
End If
On Error GoTo 0
'Resume
Valuations:
'Select Statement sheet
Sheets(2).Select
'Clear Filter
ActiveSheet.ShowAllData
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'Change Font and Size, autofit
Cells.Select
With Selection.Font
.Name = "CotySans"
.FontStyle = "Regular"
.Size = 9
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
'Format Top Row
Rows("1:1").SpecialCells(xlCellTypeConstants).Select
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
'Insert Company Code from all tabs
LastRow = ActiveSheet.UsedRange.Rows.Count
Range("A2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[1],'FBL1N Scheduled'!C1:C4,3,0), IFERROR(VLOOKUP(RC[1],'FBL1N Paid'!C1:C4,3,0),IFERROR(VLOOKUP(RC[1],'VIM Export'!C1:C5,2,0),"""")))"
Selection.AutoFill Destination:=Range("A2:A" & LastRow - 1)
'Insert Vendor Number from all tabs
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Select
ActiveCell.FormulaR1C1 = "Vendor #"
Range("B2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[1],'FBL1N Scheduled'!C1:C4,4,0), IFERROR(VLOOKUP(RC[1],'FBL1N Paid'!C1:C4,4,0),IFERROR(VLOOKUP(RC[1],'VIM Export'!C1:C5,5,0),"""")))"
Selection.AutoFill Destination:=Range("B2:B" & LastRow - 1)
'Pull Block Marker
Range("F2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-3],'VIM Export'!C1:C5,3,0),"""")"
Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F" & LastRow)
Range("F:F").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Insert VIM Status for processing/obsolete invoices
Range("L2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-9],'VIM Export'!C1:C5,4,0),"""")"
'Copy down in only visible
Selection.Copy
Range("L" & LastRow - 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
'Insert Status based on VIM Status
LastRow = ActiveSheet.UsedRange.Rows.Count - 1
Range("J2").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(RC[-3]=""R"",RC[-3]=""A""),""Blocked"",IF(RC[-8]="""",""Need Copy"",IF(RC[2]="""","""",IF(RC[2]=""Return To Vendor"",""Return To Vendor"",IF(RC[2]=""Obsolete"",""Obsolete"",""Processing"")))))"
Selection.AutoFill Destination:=Range("J2:J" & LastRow)
'Paste special over formulas
Range("A:A").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B:B").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("F:F").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("H:J").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'AutoFit Columns
Cells.Select
Cells.EntireColumn.AutoFit
Application.CutCopyMode = False
Range("L:L").Value = ""
LastRow = ActiveSheet.UsedRange.Rows.Count - 1
Range("B2:C" & LastRow).Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A2").Select
'Refresh Pivot Info for dates
Worksheets("Pivots").PivotTables("PivotTable1").PivotCache.Refresh
Worksheets("Pivots").PivotTables("PivotTable2").PivotCache.Refresh
'Hide Data Tabs
ThisWorkbook.Sheets(Array(3, 4, 5)).Visible = False
Sheets(1).Select
'Saves the file
Dim VN As String
VN = Range("A3").Value
Dim VName As String
VName = Range("B3").Value
Set objWS = CreateObject("WScript.Shell")
strDesktopPath = objWS.SpecialFolders("Desktop")
ActiveWorkbook.SaveAs strDesktopPath & "\" & VN & "." & VName & " as of " & Format(Now, "mm.dd.yyyy") & ".xlsm"
'Update final once macro completes
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

It may be that the script does not wait long enough for the button to be present.
At this one can either wait for a defined time or wait until it actually exists.
for example:
...
session.findById("wnd[0]").sendVKey 8
on error resume next
application.wait (Now + TimeValue("00:00:01")) '1 second
session.findById("wnd[1]/tbar[0]/btn[0]").press
If Err.Number = 0 Then
on error goto 0
...
or
...
session.findById("wnd[0]").sendVKey 8
on error resume next
do
application.wait (Now + TimeValue("00:00:01")) '1 second
session.findById("wnd[1]/tbar[0]/btn[0]").press
if err.number = 0 then exit do
loop
If Err.Number = 0 Then
on error goto 0
...
Regards, ScriptMan

Related

Copying the first 100 resulted rows after applying a specific criteria to my table

Does anyone know how to take only the first 100 resulted rows after this:
=COUNTIFS(R2C9:R50000C9,RC[-1])>30?
Here is my code, which I recorded it.
Thank you in advance.
I hope someone to help me.
Sub philoly_3()
'
' philoly_3 Macro
'
Sheets("Graph data").Select
Range("J1").Select
Selection.NumberFormat = "0.00"
ActiveCell.FormulaR1C1 = "Criteria"
Range("J2").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(R2C9:R50000C9,RC[-1])>30"
Range("J2").Select
Selection.AutoFill Destination:=Range("J2:J50000")
Range("J2:J50000").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Style = "Input"
Range("F2").Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Selection.AutoFilter
ActiveSheet.Range("$A$1:$J$50000").AutoFilter Field:=10, Criteria1:="TRUE"
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range("A1:I1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("All moments").Select
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit
Range("F2").Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Sheets("All moments").Select
Application.CutCopyMode = False
Sheets("All moments").Move Before:=Sheets(1)
Sheets("Graph data").Select
ActiveSheet.Range("$A$1:$J$50000").AutoFilter Field:=10
Range("I50000").Select
Selection.End(xlUp).Select
Range("I2").Select
Selection.AutoFilter
Columns("J:J").Select
Selection.Delete Shift:=xlToLeft
Range("B2").Select
philoly_11
End Sub
Maybe this can help you. Just modify to your needs and implement it in your code. For this, my data range was =B2:E481. My criteria YES/NO is in column E. I copied the first 100 ranges (B:D) that were yes in column E, and pasted them into Z2.
Sub COPY_100_FIRST_YES()
Dim i As Byte
Dim MyRanges As String
Dim MyYesRanges() As String
Dim MyFinalSelection As Range
Range("E2").Select 'first row of my YES/NO column
i = 0
Do Until ActiveCell.Value = "" Or i = 100 'Loop until you have 100 yes or there is no more data
If ActiveCell.Value = "yes" Then
i = i + 1
If MyRanges = "" Then
MyRanges = ActiveCell.Row
Else
MyRanges = MyRanges & "||" & ActiveCell.Row
End If
End If
ActiveCell.Offset(1, 0).Select
Loop
'Now I have all rows that are YES and I know the columns i want to copy, in my case is columns B to D, so
MyYesRanges() = Split(MyRanges, "||")
For i = 0 To UBound(MyYesRanges) Step 1
If i = 0 Then
Set MyFinalSelection = Range("B" & MyYesRanges(i) & ":D" & MyYesRanges(i))
Else
Set MyFinalSelection = Application.Union(MyFinalSelection, Range("B" & MyYesRanges(i) & ":D" & MyYesRanges(i)))
End If
Next i
MyFinalSelection.Copy
'Paste where you want them
Range("Z2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub

Issue in Vba code in copying and Union ranges based on particular condition

My code is giving me runtime error 424 in the highlighted line. What could be the possible reason? My rows are not getting copied. CopyRng12 creates some sort of issue.
sub grouping()
Set ws6 = Workbooks("A.xlsx").Worksheets("X1")
Set ws7 = Workbooks("B.xlsx").Worksheets("X2")
LastRowu = ws6.Cells(Rows.Count, "B").End(xlUp).Row
LastRowb = ws7.Cells(Rows.Count, "K").End(xlUp).Row
LastRowb1 = ws7.Cells(Rows.Count, "L").End(xlUp).Row
Application.Calculation = xlAutomatic
ws6.Columns("E:E").Insert Shift:=xlToRight,
CopyOrigin:=xlFormatFromLeftOrAbove
ws6.Range("E2").FormulaR1C1 = _
"=VLOOKUP(RC[-1],'[B.xlsx]X2'!C11:C12,2,0)"
ws6.Range("E2").AutoFill Destination:=ws6.Range("E2:E" & LastRowu),
Type:=xlFillDefault
With ws6.UsedRange
.Copy
.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
ws6.Cells.Replace "#N/A", "Company Code Not Found", xlWhole
Workbooks("A.xlsx").Worksheets("X1").Activate
ws6.Columns("D:D").Select
Selection.Copy
ws6.Columns("A:A").Select
Selection.Insert Shift:=xlToRight
For q = LastRowu - 1 To 1 Step -1
If ws6.Cells(q, "F").Value = "G1" Then
**If Not CopyRng12 Is Nothing Then
Set CopyRng12 = Application.Union(CopyRng12, ws6.Rows(q))**
Else
Set CopyRng12 = ws6.Rows(q)
End If
End If
Next q
Set wbmm = Workbooks("G1.xlsx")
Workbooks("G1.xlsx").Activate
Dim wsmm As Worksheet
Set wsmm = wbmm.Worksheets("X1")
Workbooks("G1.xlsx").Worksheets("X1").Activate
CopyRng12.Copy
Worksheets("X2").ClearContents
ActiveSheet.Paste
End Sub

MID and CONCATENATE in VBA

I'm having the following issue: I recorded a Macro of me using some MID and CONCATENATE formulas after my macro reorders a ton of data. When I run the macro, I get a #REF error, which I understand. However, is there a VBA Code that could remove that or somehow use the MID and CONCATENATE without creating the #REF error? My code is below and any help would be much appreciated.
Sub Macro4()
'
' Macro4 Macro
'
'
Sheets("Sheet2").Select
Cells.Select
Range("D29").Activate
Selection.ClearContents
Selection.End(xlUp).Select
Selection.End(xlToLeft).Select
Sheets("Sheet1").Select
'
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 1), Array(1, 1), Array(16, 1), Array(21, 1), Array(37, 1), _
Array(42, 1), Array(58, 1), Array(63, 1), Array(79, 1), Array(84, 1), Array(100, 1), Array( _
105, 1), Array(121, 1), Array(129, 1)), TrailingMinusNumbers:=True
Rows("1:6").Select
Selection.Delete Shift:=xlUp
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Columns("B:B").Select
Selection.Delete Shift:=xlToLeft
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
Columns("D:D").Select
Selection.Delete Shift:=xlToLeft
Columns("E:E").Select
Selection.Delete Shift:=xlToLeft
Columns("F:F").Select
Selection.Delete Shift:=xlToLeft
Columns("G:G").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Dim lastRow&, g&
Dim findStr$
findStr = "Planning of"
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For g = lastRow To 1 Step -1 ' change this to 2 if you have headers
If Cells(g, 1).Value = findStr Then
'Range(Rows(i), Rows(i - 4)).Select
Range(Rows(g), Rows(g - 4)).EntireRow.Delete
End If
Next g
Dim arr() As Variant
Dim p As Integer, i&
Dim ws As Worksheet
Dim tws As Worksheet
Dim t As Integer
Dim c As Long
Dim u As Long
Set ws = ActiveSheet
Set tws = Worksheets("Sheet2")
i = 1
With ws
Do Until i > 100000
u = 0
For c = 1 To .Cells(1, .Columns.Count).End(xlToLeft).Column
'If c = .Cells(1, .Columns.Count).End(xlToLeft).Column And .Cells(i, c) <> "" Then
ReDim arr(0) As Variant
p = 0
t = 0
Do Until .Cells(i + p, c) = "" And t = 1
If .Cells(i + p, c) = "" Then
t = 1
Else
arr(UBound(arr)) = .Cells(i + p, c)
ReDim Preserve arr(UBound(arr) + 1)
End If
p = p + 1
Loop
If p > u Then
u = p
End If
If c = .Cells(1, .Columns.Count).End(xlToLeft).Column Then
If .Cells(i + p, c).End(xlDown).Row > 100000 And .Cells(i + p, 1).End(xlDown).Row < 100000 Then
i = .Cells(i + u, 1).End(xlDown).Row
Else
i = .Cells(i + p, c).End(xlDown).Row
End If
End If
tws.Cells(tws.Rows.Count, 1).End(xlUp).Offset(1).Resize(, UBound(arr) + 1) = arr
Next c
Loop
End With
With tws
.Rows(1).Delete
For i = .Cells(1, 1).End(xlDown).Row To 2 Step -1
If Left(.Cells(i, 1), 4) <> Left(.Cells(i - 1, 1), 4) Then
.Rows(i).EntireRow.Insert
End If
Next i
End With
'
' Macro6 Macro
'
'
'Sheets("Sheet2").Select
'Range("A1:M67").Select
'Selection.Copy
'Sheets("Output").Select
'Range("A3").Select
'ActiveSheet.Paste
'Range("A1").Select
ActiveCell.FormulaR1C1 = "=IF(Sheet2!RC="""","""",Sheet2!RC)"
Range("B1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[1],5,4)"
Range("C1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC,1,3)"
Range("D1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC,6,3)"
Range("E1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-1],1,4)"
Range("F1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-2],10,4)"
Range("F2").Select
Columns("F:F").EntireColumn.AutoFit
Range("G1").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-3]="""","""",RC[-3])"
Range("H1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-3],5,3)"
Range("H1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-3],6,3)"
Range("I1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-4],1,4)"
Range("J1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-5],10,4)"
Range("K1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-5],6,3)"
Range("K2").Select
Columns("K:K").EntireColumn.AutoFit
Range("G1").Select
Selection.Copy
Range("K1").Select
ActiveSheet.Paste
Range("L1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-6],6,3)"
Range("M1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-7],1,4)"
Range("N1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-8],10,4)"
Range("O1").Select
ActiveCell.FormulaR1C1 = ""
Range("K1").Select
Selection.Copy
Range("O1").Select
ActiveSheet.Paste
Range("O1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IF(RC[-3]="""","""",RC[-3])"
Range("P1").Select
Columns("P:P").ColumnWidth = 7.71
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-9],6,3)"
Range("Q1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-10],1,4)"
Range("R1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-11],10,4)"
Range("O1").Select
Selection.Copy
Range("S1").Select
ActiveSheet.Paste
Range("T1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-12],6,3)"
Range("U1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-13],1,4)"
Range("V1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-14],10,3)"
Range("V1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-14],10,4)"
Range("V2").Select
Columns("U:U").EntireColumn.AutoFit
Range("S1").Select
Selection.Copy
Range("W1").Select
ActiveSheet.Paste
Range("X1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-15],6,3)"
Range("Y1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!R[10]C[-16],1,4)"
Range("Y1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-16],1,4)"
Range("Z1").Select
ActiveCell.FormulaR1C1 = ""
Range("W1").Select
Selection.Copy
Range("Z1").Select
ActiveSheet.Paste
Range("Z1").Select
Columns("Z:Z").EntireColumn.AutoFit
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-17],10,4)"
Range("AA1").Select
ActiveCell.FormulaR1C1 = ""
Range("W1").Select
Selection.Copy
Range("AA1").Select
ActiveSheet.Paste
Range("AB1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-18],6,3)"
Range("AC1").Select
ActiveCell.FormulaR1C1 = "=Sheet2!R[113]C[-19]"
Range("AC1").Select
ActiveCell.FormulaR1C1 = "eet2!J114"
Range("AC1").Select
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-19],1,4)"
Range("AA1").Select
Selection.Copy
Range("AD1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=MID(Sheet2!RC[-20],10,4)"
Range("W1").Select
Selection.Copy
Range("AD1").Select
ActiveSheet.Paste
Range("AD1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IF(OR(RC[-3]="""",AE=""""),"""",RC[-3])"
Range("AD1").Select
ActiveCell.FormulaR1C1 = "=IF(OR(RC[-3]="""",RC[1]=""""),"""",RC[-3])"
Range("A1:AD1").Select
Selection.AutoFill Destination:=Range("A1:AD123"), Type:=xlFillDefault
Range("A1:AD123").Select
ActiveWindow.SmallScroll Down:=-108
Range("V23").Select
ActiveWindow.SmallScroll Down:=-21
Columns("AD:AD").Select
Selection.Copy
Columns("G:G").Select
ActiveSheet.Paste
Columns("K:K").Select
ActiveSheet.Paste
Columns("O:O").Select
ActiveSheet.Paste
Columns("S:S").Select
ActiveSheet.Paste
Columns("W:W").Select
ActiveSheet.Paste
Columns("AA:AA").Select
ActiveSheet.Paste
ActiveWindow.SmallScroll Down:=-27
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.End(xlToLeft).Select
Sheets("Sheet4").Select
Range("A3").Select
ActiveWindow.SmallScroll Down:=-6
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IF(Sheet3!R[-2]C="""","""",Sheet3!R[-2]C)"
Range("B3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C,"" "",Sheet3!R[-2]C[1],Sheet3!R[-2]C[2],"" "",Sheet3!R[-2]C[3])"
Range("B3").Select
Selection.Copy
Range("C3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[3],"" "",Sheet3!R[-2]C[4],Sheet3!R[-2]C[5],"" "",Sheet3!R[-2]C[6])"
Range("D3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[6],"" "",Sheet3!R[-2]C[7],Sheet3!R[-2]C[8],"" "",Sheet3!R[-2]C[9])"
Range("E3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[9],"" "",Sheet3!R[-2]C[10],Sheet3!R[-2]C[11],"" "",Sheet3!R[-2]C[12])"
Range("F3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[12],"" "",Sheet3!R[-2]C[13],Sheet3!R[-2]C[14],"" "",Sheet3!R[-2]C[15])"
Range("G3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[15],"" "",Sheet3!R[-2]C[16],Sheet3!R[-2]C[17], ,Sheet3!R[-2]C[18])"
Range("G3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[15],"" "",Sheet3!R[-2]C[16],Sheet3!R[-2]C[17],"" "",Sheet3!R[-2]C[18])"
Range("H3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[18],"" "",Sheet3!R[-2]C[19],Sheet3!R[-2]C[20],"" "")"
Range("H3").Select
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(Sheet3!R[-2]C[18],"" "",Sheet3!R[-2]C[19],Sheet3!R[-2]C[20],"" "",Sheet3!R[-2]C[21])"
Range("H4").Select
Sheets("Sheet3").Select
ActiveWindow.SmallScroll Down:=-12
Sheets("Sheet4").Select
Range("A3:H3").Select
Selection.AutoFill Destination:=Range("A3:H193"), Type:=xlFillDefault
Range("A3:H193").Select
ActiveWindow.SmallScroll Down:=-201
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Output").Select
Range("A1").Select
ActiveWindow.SmallScroll Down:=-12
Sheets("Sheet4").Select
Cells.Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet4").Select
ActiveWindow.SmallScroll Down:=-48
Range("A116").Select
Selection.End(xlUp).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Output").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End Sub
I couldn't figure out how to fix the VBA so I simply ran the code without the MID and CONCATENATE in there. Once I did that, I copy and pasted my results into a new tab and entered the equations.

VBA Error 1004: PasteSpecial method of range class failed

I'm having a bit of trouble with any kind of paste method I use at the moment.
Data from one sheet must be cut and pasted to another, but I'm not sure what I'm missing.
The error occurs here, shortly after the commented "HERE" :
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Full code can be found below, thanks for any replies.
Option Explicit
Public Sub Workbook_Open()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wb As Variant
Dim wsName As Variant
Dim blastrow As Variant
Dim flastrow As Variant
Dim lastrow As Variant
ActiveWorkbook.Sheets("combined").Select
Range("A1:U9999").ClearContents
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("G:\BS\Josh Whitfield\Credit_Chasing\NEW PROCESS\")
'file level loop
While (file <> "")
If InStr(file, ".xlsx") > 0 Then
Workbooks.Open "G:\BS\Josh Whitfield\Credit_Chasing\NEW PROCESS\" & file
wb = ActiveWorkbook.Name
'ws = ActiveSheet.Name
Dim ws As Worksheet
'worksheet/tab level loop
For Each ws In ActiveWorkbook.Worksheets
ws.Activate
wsName = ws.Name
'andrew code (09/12/2015)
blastrow = Workbooks("Copy of merge.xlsb").Worksheets("Combined").Range("A" & Rows.Count).End(xlUp).Row + 1
If blastrow = 2 Then blastrow = 1
Workbooks("Copy of merge.xlsb").Worksheets("Combined").Range("A" & blastrow & ":XFD" & blastrow).Value = _
Workbooks(wb).Worksheets(wsName).Range("A1:XFD1").Value
lastrow = Range("A" & Rows.Count).End(xlUp).Row
'finding status column
Range("M1").Select
Do Until ActiveCell.Value = "Status" Or ActiveCell.Column > 100
If Range("A2") = "" Then
GoTo there
End If
ActiveCell.Offset(0, 1).Select
Loop
'looping through
Do Until ActiveCell.Row > lastrow
If ActiveCell.Value = "Solved" Then 'HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
wb = ActiveWorkbook.Name
wb = Replace(wb, ".xlsx", "")
ActiveCell.EntireRow.Cut
Workbooks("copy of merge.xlsb").Activate
'find matching company
Range("E1").Select
While ActiveCell.Value <> "CoName"
ActiveCell.Offset(0, 1).Select
Wend
Do Until ActiveCell.Value = wb
ActiveCell.Offset(1, 0).Select
If ActiveCell.Value = "" Then
ActiveCell.EntireRow.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
Loop
'first cell in row select
ActiveSheet.Cells(ActiveCell.Row, 1).Select
'find matching ws
If ws = "Be Wiser" Then
Do Until ActiveCell.Value = "BW"
ActiveCell.Offset(1, 0).Select
Loop
ElseIf ws = "Insure Wiser" Then
Do Until ActiveCell.Value = "IW"
ActiveCell.Offset(1, 0).Select
Loop
ElseIf ws = "Call Wiser" Then
Do Until ActiveCell.Value = "CW"
ActiveCell.Offset(1, 0).Select
Loop
ElseIf ws = "Quote Wiser" Then
Do Until ActiveCell.Value = "QW"
ActiveCell.Offset(1, 0).Select
Loop
ElseIf ws = "Be Wiser Business" Then
Do Until ActiveCell.Value = "BWB"
ActiveCell.Offset(1, 0).Select
Loop
ElseIf ws = "Younger But Wiser" Then
Do Until ActiveCell.Value = "YBW"
ActiveCell.Offset(1, 0).Select
Loop
End If
'insert row and paste
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
'lastrow = Range("A" & Rows.Count).End(xlUp).Row + 1
'Range("A" & lastrow).Select
'ActiveSheet.Paste
ws.Activate
lastrow = Range("A" & Rows.Count).End(xlUp).Row
Cells.Select
ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range("A2:A19" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
.SetRange Range("A1:U" & lastrow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("M1").Select
Do Until ActiveCell.Value = "Status" Or ActiveCell.Column > 100
ActiveCell.Offset(0, 1).Select
Loop
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
there:
'here
flastrow = Workbooks("Copy of merge.xlsb").Worksheets("Combined").Range("A" & Rows.Count).End(xlUp).Row
If blastrow = flastrow Then
Workbooks("Copy of merge.xlsb").Worksheets("Combined").Activate
Range("A" & blastrow).Select
ActiveCell.EntireRow.Delete
Workbooks(wb).Worksheets(wsName).Activate
End If
Next ws
Workbooks(wb).Close False
End If
file = Dir
Wend
Call storeFileNames
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
As has been noted, you really ought to rewrite this, but as a quick fix, add a range variable:
Dim rgCut as Excel.Range
then instead of this:
ActiveCell.EntireRow.Cut
use:
set rgCut = ActiveCell.EntireRow
and then replace this:
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
with this:
rgCut.Cut Destination:=Selection.Cells(1)

Subscipt out of range first time I run it but doesn't give error on next runs

I get "subscript out of range" error on line:
Set DataSheet = Worksheets(DataSheetName)
This only happens the first time I run it. If I re-run the code after the error, the macro works fine.
Complete code:
Sub iGetData()
Dim ValidatorWB As Workbook
Dim PopDetail As Worksheet
Dim DataSheetName As String
Dim DataWB As Workbook
Dim DataSheet As Worksheet
Dim Ret
Dim DWBName As String
Dim FNOrder As String
Dim FNOrdCol As String
Set PopDetail = Worksheets("PopulateWireframe")
Set ValidatorWB = Workbooks(ActiveWorkbook.Name)
DataSheetName = Range("F18").Value
FNOrder = Range("F33").Value
Application.ScreenUpdating = False
'Open data file
Ret = IsWorkBookOpen(PopDetail.Range("C18").Value)
If Ret = False Then
Workbooks.Open PopDetail.Range("C18").Value
DataFileName = ActiveWorkbook.Name
Set DataWB = Workbooks(DataFileName)
Set DataSheet = Worksheets(DataSheetName)
Dim FilterColumn As String
Dim FilterCriteria As String
Dim ColumnNumber As Integer
'Set filter
With DataSheet
If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
End With
ValidatorWB.Activate
PopDetail.Activate
For x = 21 To 30
If Range("E" & x).Value <> "" And Range("F" & x).Value <> "" Then
FilterColumn = PopDetail.Range("E" & x).Value
FilterCriteria = PopDetail.Range("F" & x).Value
DataWB.Activate
DataSheet.Activate
DataSheet.Range("A1").Select
Selection.End(xlToLeft).Select
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Find(What:=FilterColumn, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ColumnNumber = ActiveCell.Column
DataSheet.AutoFilterMode = False
DataSheet.Range("A1").AutoFilter Field:=ColumnNumber, Criteria1:=FilterCriteria
End If
ValidatorWB.Activate
PopDetail.Activate
'x = x + 1
Next x
DataWB.Activate
DataSheet.Activate
'Alpahebtical order
DataSheet.Range("A1").Select
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Find(What:=FNOrder, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
FNOrdCol = ActiveCell.Address
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=Range(FNOrdCol), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange DataSheet.Cells
.header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Copy data
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Paste data to validator
ValidatorWB.Activate
ValidatorWB.Sheets.Add().Name = "ValidatorData"
ActiveCell.Offset(3, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
ActiveCell.Columns("A:A").EntireColumn.ColumnWidth = 15
Application.CutCopyMode = False
'DataWB.Close savechanges:=False
If DataWB.Windows(1).Visible = True Then
DataWB.Windows(1).Visible = False
End If
Application.ScreenUpdating = True
PopDetail.Activate
Else
DWBName = GetFilenameFromPath(PopDetail.Range("C18").Value)
Set DataWB = Workbooks(DWBName)
DataWB.Activate
Set DataSheet = Worksheets(DataSheetName)
DataSheet.Activate
With DataSheet
If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
End With
ValidatorWB.Activate
PopDetail.Activate
For x = 21 To 30
If Range("E" & x).Value <> "" And Range("F" & x).Value <> "" Then
FilterColumn = PopDetail.Range("E" & x).Value
FilterCriteria = PopDetail.Range("F" & x).Value
DataWB.Activate
DataSheet.Activate
DataSheet.Range("A1").Select
Selection.End(xlToLeft).Select
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Find(What:=FilterColumn, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ColumnNumber = ActiveCell.Column
DataSheet.AutoFilterMode = False
DataSheet.Range("A1").AutoFilter Field:=ColumnNumber, Criteria1:=FilterCriteria
End If
ValidatorWB.Activate
PopDetail.Activate
'x = x + 1
Next x
DataWB.Activate
DataSheet.Activate
'Alpahebtical order
DataSheet.Range("A1").Select
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Find(What:=FNOrder, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
FNOrdCol = ActiveCell.Address
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=Range(FNOrdCol), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange DataSheet.Cells
.header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Copy data
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Paste data to validator
ValidatorWB.Activate
ValidatorWB.Sheets.Add().Name = "ValidatorData"
ActiveCell.Offset(3, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
ActiveCell.Columns("A:A").EntireColumn.ColumnWidth = 15
Application.CutCopyMode = False
'DataWB.Close savechanges:=False
If DataWB.Windows(1).Visible = True Then
DataWB.Windows(1).Visible = False
End If
Application.ScreenUpdating = True
PopDetail.Activate
End If
End Sub
Figured out the problem. Excel usually sets a newly opened workbook as the active workbook which is why I used activeworkbook.name to define a workbook but the newly opened workbook was not being set as the active workbook.
Did this:
Workbooks.Open PopDetail.Range("C18").Value
DataFileName = GetFilenameFromPath(PopDetail.Range("C18").Value)
Set DataWB = Workbooks(DataFileName)
DataWB.Activate
Set DataSheet = Worksheets(DataSheetName)
Instead of:
Workbooks.Open PopDetail.Range("C18").Value
DataFileName = ActiveWorkbook.Name
Set DataWB = Workbooks(DataFileName)
Set DataSheet = Worksheets(DataSheetName)
GetFilename Code:
Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function