How to create dynamic ranges and Improving vba Code - excel

I Have a little bit of code (below) that I would like to improve as I find it a little clunky with regards to the ranges as they vary daily, Ideally I would like to use last row instead of using a massive range but, sadly I am not that clever :(
this is the code, if anyone fancies taking a look to improve on I would be greatly appreciative, I think the process is self explanatory (i.e auto filter and copying from one sheet to another)
Sub Refresh_click()
Set DbExtract = ThisWorkbook.Sheets("Sheet1")
Set DuplicateRecords = ThisWorkbook.Sheets("Sheet2")
Sheets("Sheet2").Unprotect
Range("A4:A50").Select
Application.CutCopyMode = False
Selection.ClearContents
Sheets("Sheet1").Select
ActiveSheet.ListObjects("Table22").Range.AutoFilter Field:=23, Criteria1:= _
"="
DbExtract.Range("F2:F99999").SpecialCells(xlCellTypeVisible).Copy
DuplicateRecords.Range("A4:A50").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Protect
Sheets("Sheet1").Select
ActiveSheet.ListObjects("Table22").Range.AutoFilter Field:=23
MsgBox "Log - Updated"
End Sub

Try in this way, please:
Sub Refresh_click()
Dim DbExtract As Worksheet, DuplicateRecords As Worksheet, lastFRow As Long
Set DbExtract = ThisWorkbook.Sheets("Sheet1")
Set DuplicateRecords = ThisWorkbook.Sheets("Sheet2")
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
.CutCopyMode = False
End With
With DuplicateRecords
.Unprotect
.Range("A4:A50").ClearContents
End With
DbExtract.ListObjects("Table22").Range.AutoFilter field:=23, Criteria1:="="
lastFRow = DbExtract.Range("F" & rows.count).End(xlUp).row 'last row of F:F col
DbExtract.Range("F2:F" & lastFRow).SpecialCells(xlCellTypeVisible).Copy
DuplicateRecords.Range("A4").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
DuplicateRecords.Protect
DbExtract.ListObjects("Table22").Range.AutoFilter field:=23
With Application
.Calculation = xlCalculationAutomatic
.EnableEvents = True
.ScreenUpdating = True
End With
MsgBox "Log - Updated"
End Sub
Please, test it and send some feedback. I couldn't test it...

Copy Using AutoFilter
Adjust the values in the constants section.
The Code
Option Explicit
Sub Refresh_click()
Const srcName As String = "Sheet1"
Const srcTblName As String = "Table22"
Const srcCol As Long = 6
Const srcField As Long = 23
Const srcCrit As String = "="
Const dstName As String = "Sheet2"
Const dstFirst As String = "A4"
Dim wb As Workbook: Set wb = ThisWorkbook
Dim cel As Range
Dim rng As Range
Dim Updated As Boolean
With wb.Worksheets(dstName)
.Unprotect
Set cel = .Range(dstFirst)
cel.Resize(cel.Worksheet.Rows.Count - cel.Row + 1).ClearContents
With wb.Worksheets(srcName).ListObjects(srcTblName)
.Range.AutoFilter
Set rng = .ListColumns(srcCol).Range _
.Resize(.ListRows.Count).Offset(1)
'Debug.Print rng.Address
.Range.AutoFilter Field:=srcField, Criteria1:=srcCrit
On Error Resume Next
rng.SpecialCells(xlCellTypeVisible).Copy
On Error GoTo 0
If Application.CutCopyMode = xlCopy Then
cel.PasteSpecial xlPasteValues
Updated = True
End If
.Range.AutoFilter
End With
.Protect
End With
If Updated Then
MsgBox "Log updated.", vbInformation, "Success"
Else
MsgBox "Log not updated.", vbCritical, "Fail"
End If
End Sub

Related

Excel VBA will not close my opened workbook

I am pretty much new to VBA and have been trying to learn, with this I have created a code that opens another work book and combines all data to a database file and then copy this to my current open file, the problem I have is that it will not close the workbook and takes a long time doing so. Any ideas please?.
'''
Option Explicit
Sub GasStockReport()
Dim wb As String
Dim st As String
Dim path As String
path = "C:\Users\si2066\OneDrive - ENGIE\Desktop\MP Templates\MP - Stock Control\"
wb = "Gas Stock Take v2"
Workbooks.Open path & wb
Dim sh As Worksheet
Dim destsh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Database").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set destsh = ActiveWorkbook.Worksheets.Add
destsh.Name = "Database"
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> destsh.Name Then
Last = GetLastRow(destsh, 1)
With sh
Set CopyRng = sh.Range("A2:K" & GetLastRow(sh, 1))
End With
If Last + CopyRng.Rows.Count > destsh.Rows.Count Then
MsgBox "There are not enough rows in the Destsh"
GoTo ExitTheSub
Else
CopyRng.Copy IIf(Last = 1, destsh.Cells(1, "b"), destsh.Cells(Last + 1, "b"))
End If
If Last = 1 Then
destsh.Cells(Last, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
Else
destsh.Cells(Last + 1, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
End If
End If
Next
ExitTheSub:
Application.Goto destsh.Cells(1)
destsh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Range("A1").Select
Range(Selection, ActiveCell.End(xlDown).End(xlToRight)).Select
Selection.Copy
ActiveWindow.SelectedSheets.Visible = False
ThisWorkbook.Sheets("Stock History").Activate
Range("N1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.DisplayAlerts = False
On Error Resume Next
Workbooks("Gas Stock Take v2").Close SaveChanges:=True
On Error GoTo 0
Application.DisplayAlerts = True
ThisWorkbook.Sheets("Stock Take").Activate
Call Click
End Sub
Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1)
As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function
'''
Your error handling is fine. Using On Error GoTo 0 turns off On Error Resume Next.
I think the issue is the amount of data you're leaving on the clipboard after copy and paste. If you use .copy and .paste always follow that up with Application.CutCopyMode = False

Trying to set text in a colum based on a match on a different sheet

I am creating a inventory control workbook and I am looking to have a column with the words "Order Placed" once I have clicked on the button to place order. I want to make sure that it is based on the right criteria. Currently in I am using a formula to place that text but once I clear the order form that goes away because its using an index match function within an if statement.
This is my current Order Placed Sub
Sub orderPlaced()
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim startCell As range, lastRow As Long, lastCol As Long, ws As Worksheet
Set ws = Sheets("Re-Order List")
'This part Copies the requested information
Sheets("Re-Order List").Select
range("A1").Select
Application.CutCopyMode = False
Selection.Copy
'This part Pastes the requested information in the history
Sheets("Order History").Select
Selection.End(xlDown).Select
range("A65536").Select
Selection.End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteAllExceptBorders, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'This part Copies the requested information
Sheets("Re-Order List").Select
Set startCell = range("A3")
lastRow = ws.Cells(ws.Rows.Count, startCell.Column).End(xlUp).Row
lastCol = ws.Cells(startCell.Row, ws.Columns.Count).End(xlToLeft).Column
ws.range(startCell, ws.Cells(lastRow, lastCol)).Select
Application.CutCopyMode = False
Selection.Copy
'This part Pastes the requested information in the history
Sheets("Order History").Select
Selection.End(xlDown).Select
range("A65536").Select
Selection.End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'This part adds orderplaced below order form
Sheets("Order History").Select
range("A65536").Select
Selection.End(xlUp).Offset(2, 0).Select
With Selection
.Value = "Order Placed :"
.HorizontalAlignment = xlRight
End With
'This part adds the date
Sheets("Order History").Select
range("B65536").Select
Selection.End(xlUp).Offset(2, 0).Select
With Selection
.Value = Date
.NumberFormat = "dd/mmm/yyyy"
.HorizontalAlignment = xlLeft
End With
'this will set the comment in inventory to ordered
'*************************
'NEEDED CODE WILL GO HERE
'*************************
Sheets("Inventory").Select
range("K6:K400").ClearContents
'This part Clears the order form
Sheets("Re-Order List").Select
range("A4:D5000").ClearContents
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
This is my Add to Order Sub
Sub add2Order()
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim C As range, rng As range, D As range, Rng1 As range, mnrng As range, acrng As range
Sheets("Inventory").Select
Set rng = range("K6:K400")
For Each C In rng
If InStr(1, C, "X") > 0 Then
'first select material number and name
Set mnrng = range(C.Offset(0, -9), C.Offset(0, -8))
Application.CutCopyMode = False
mnrng.Copy
'paste in reorder sheet
Sheets("Re-Order List").Select
Selection.End(xlDown).Select
range("A400").Select
Selection.End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = True
End If
Next
Sheets("Inventory").Select
Set Rng1 = range("K6:K400")
For Each D In Rng1
If InStr(1, D, "X") > 0 Then
'Second select amount and cost
Set acrng = range(D.Offset(0, -2), D.Offset(0, -1))
Application.CutCopyMode = False
acrng.Copy
'paste in reorder sheet
Sheets("Re-Order List").Select
Selection.End(xlDown).Select
range("C400").Select
Selection.End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = True
End If
Next
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Code that is close is as follows
Sub test()
'
Dim w1 As Worksheet, w2 As Worksheet
Dim C As range, a As range
Set w1 = Sheets("Inventory")
Set w2 = Sheets("Re-Order List")
With w1
For Each C In .range("$A$6:$A$400")
Set a = w2.Columns(1).Find(C.Value, LookAt:=xlWhole)
If Not a Is Nothing Then
If IsEmpty(.Cells(C.Row, 1)) And .Cells(C.Row, 1).Value = w2.Cells(a.Row, 1) Then
w1.Cells(C.Row, 12).Value = "Order Placed"
End If
End If
Next C
End With
End Sub
This is the last piece to this puzzle to get it how I want it to work, I know for sure I will only have less than 400 materials to manage and if that grows I can update then but any help would be fantastic.
This is the drive link for the actual sheet
This isn't an answer until you tell us exactly where do you want to place the information
I refactored your code so you don't use select and added some pseudo code that may give you a hint
Public Sub orderPlaced()
' Turn off stuff to speed up process
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
'This part Copies the requested information
Dim reorderListSheet As Worksheet
Set reorderListSheet = ThisWorkbook.Worksheets("Re-Order List")
reorderListSheet.Range("A1").Copy
'This part Pastes the requested information in the history
Dim orderHistorySheet As Worksheet
Set orderHistorySheet = ThisWorkbook.Worksheets("Order History")
orderHistorySheet.Cells(orderHistorySheet.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteAllExceptBorders, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
' Find last row in reorder sheet
Dim reorderLastRow As Long
reorderLastRow = reorderListSheet.Cells(reorderListSheet.Rows.Count, "A").End(xlUp).Row
' Find last column in reorder sheet
Dim reorderLastColumn As Long
reorderLastColumn = reorderListSheet.Cells(3, reorderListSheet.Columns.Count).End(xlToLeft).Column
'This part Copies the requested information
Dim reorderStartCell As Range
Set reorderStartCell = reorderListSheet.Range("A3")
reorderListSheet.Range(reorderStartCell, reorderListSheet.Cells(reorderLastRow, reorderLastColumn)).Copy
'This part Pastes the requested information in the history
Dim orderHistoryLastRow As Long
orderHistoryLastRow = orderHistorySheet.Cells(orderHistorySheet.Rows.Count, "A").End(xlUp).Row
orderHistorySheet.Range("A" & orderHistoryLastRow).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
'This part adds orderplaced below order form
With orderHistorySheet.Range("A" & orderHistoryLastRow).Offset(3, 0)
.Value = "Order Placed :"
.HorizontalAlignment = xlRight
End With
'This part adds the date
With orderHistorySheet.Range("B" & orderHistoryLastRow).Offset(3, 0)
.Value = Date
.NumberFormat = "dd/mmm/yyyy"
.HorizontalAlignment = xlLeft
End With
'this will set the comment in inventory to ordered
'*************************
' THIS NEXT IS PSEUDO CODE BECAUSE I COULDN'T UNDERSTAND YOUR REQUIREMENT
Dim targetCell As Range
Set targetCell = orderHistorySheet.Range("A1").Value = "=IFERROR(IF(INDEX(Table2[Material Number],MATCH(C6,Table2[Name],0)) = [#[Material Number]],""Order Placed"",""""),"""")"
' turn that into a value
targetCell.Value = targetCell.Value
'*************************
' Clear inventory sheet
Dim inventorySheet As Worksheet
Set inventorySheet = ThisWorkbook.Worksheets("Inventory")
inventorySheet.Range("K6:K400").ClearContents
'This part Clears the order form
reorderListSheet.Range("A4:D5000").ClearContents
' Turn on stuff again
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
I FIGURED IT OUT!!!!!!!!
'this will set the comment in inventory to ordered
'*************************
Dim r1 As range
Dim r2 As range
Dim cell As range
Set r1 = Sheets("Inventory").range("B6:B400")
Set r2 = Sheets("Re-Order List").range("A4:A400")
For Each cell In r1
If IsError(Application.Match(cell, r2, 0)) Then
cell.Offset(, 12) = ""
Else
cell.Offset(, 12) = "Order Placed"
' If found I need the value from Sheet2 that is in Col B of the matching row.
End If
Next cell
'*************************

Cant get "Am I sure I want to delete" pop up to not come up when deleting row

I am using the below code to delete a row based on if the value is empty or not.
When running the code - It still pops up asking if I want to delete the data. I don't want that.
Set ws1 = ThisWorkbook.Worksheets("Verification Needed")
Set ws2 = ThisWorkbook.Worksheets("Text Only")
ws1.Range("A1:H999").AutoFilter Field:=6, Criteria1:=""
ws1.Range("A2:H999").SpecialCells(xlCellTypeVisible).Delete
Application.CutCopyMode = False
On Error Resume Next
ws1.ShowAllData
On Error GoTo 0
ws2.Range("A1:F999").AutoFilter Field:=6, Criteria1:=""
ws2.Range("A2:F999").SpecialCells(xlCellTypeVisible).Delete
Application.CutCopyMode = False
On Error Resume Next
ws2.ShowAllData
On Error GoTo 0
Here is the whole code:
Sub Tbl_CopyPaste_Verification()
Dim wsSheet As Worksheet
Dim Tbl As ListObject
Dim Rng As Range
Dim ChkSht As Worksheet
Dim Chk As Range
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Please Select Current Day Report",
FileFilter:="Excel
Files(*.xls*),*xls*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A2", Range("A2").End(xlToRight).End(xlDown)).Copy
ThisWorkbook.Worksheets("Current Day").Range("A2").PasteSpecial xlPasteValues
Application.CutCopyMode = False
OpenBook.Close
End If
FileToOpen = Application.GetOpenFilename(Title:="Please Select Previous Days Report",
FileFilter:="Excel Files(*.xls*),*xls*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A2", Range("A2").End(xlToRight).End(xlDown)).Copy
ThisWorkbook.Worksheets("Previous Days").Range("A2").PasteSpecial xlPasteValues
Application.CutCopyMode = False
OpenBook.Close
End If
Set ChkSht = ActiveWorkbook.Worksheets(3)
Set Chk = ChkSht.Range("A2")
If Chk = "" Then
MsgBox ("There is no data to process")
Exit Sub
Else
Sheets("Verification Needed").Activate
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range("A2:F2").Select
Selection.AutoFill Destination:=Range( _
"VN[[Appointment Start Date]:[Patient Primary Carrier Name]]")
Range("VN[[Appointment Start Date]:[Patient Primary Carrier Name]]").Select
Sheets("Text Only").Activate
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFill Destination:=Range("TO")
Range("TO").Select
Sheets("Text Only").Activate
Sheets("Text Only").Range("A2:F2").Select
Sheets("Text Only").Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Text Only").Range("A2").PasteSpecial Paste:=xlPasteValues
Sheets("Verification Needed").Activate
Sheets("Verification Needed").Activate
Sheets("Verification Needed").Range("A2:F2").Select
Sheets("Verification Needed").Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Verification Needed").Range("A2").PasteSpecial Paste:=xlPasteValues
Set ws1 = ThisWorkbook.Worksheets("Verification Needed")
Set ws2 = ThisWorkbook.Worksheets("Text Only")
ws1.Range("A1:H999").AutoFilter Field:=6, Criteria1:=""
ws1.Range("A2:H999").SpecialCells(xlCellTypeVisible).Delete
Application.CutCopyMode = False
On Error Resume Next
ws1.ShowAllData
On Error GoTo 0
ws2.Range("A1:F999").AutoFilter Field:=6, Criteria1:=""
ws2.Range("A2:F999").SpecialCells(xlCellTypeVisible).Delete
Application.CutCopyMode = False
On Error Resume Next
ws2.ShowAllData
On Error GoTo 0
Sheets("Verification Needed").Activate
Range("A1").Select
Application.ScreenUpdating = True
End If
End Sub
change code as below.
When deleting data, it is the content to select whether to push to the left, push upward, or delete the entire row.
from
Range("A2:F999").SpecialCells(xlCellTypeVisible).Delete
to
Range("A2:F999").SpecialCells(xlCellTypeVisible).EntireRow.Delete

Excel ignoring code that works in other workbooks

I have code that runs in several other workbooks but seems to be ignored in a specific one.
The only difference I can see between the ones that work and the one that doesn't, is a line that has SaveAs Filename: vs SaveAs FileName:. Somehow I cannot imagine that would cause the whole script to be ignored but??
The other thing is when I attempt to change the code from Filename to FileName, excel changes it back as soon as I go to the next line.
Corrupt file?
Apologies for the sloppy code... :(
```Sub Create_Individual_Files()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Dim i As Integer
Dim x As String
Dim Lastrow As Long
Dim NewBook As Workbook
Dim Sourcewb As Workbook: Set Sourcewb = ThisWorkbook
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim FName As String
Dim Fpath As String
Dim FName2 As String
Fpath = Sheets("Variables").Range("B1").Text
FName = Sheets("Variables").Range("B9").Text
FName2 = Sheets("Variables").Range("B2").Text
'Find the last row of data in each tab.
Lastrow = Sourcewb.Sheets(1).Cells(Sourcewb.Sheets(1).Rows.Count, "A").End(xlUp).Row
'This section creates each new file, retaining all formulas, from the existing tabs in the master workbook. Then saves the file with the individuals name.
For i = 2 To Lastrow
x = Sourcewb.Sheets(1).Range("A" & i).Value
Sourcewb.Sheets(Array("Summary", "Pivot", "Data", "Modifier %", "Modifier Dollar", "Variables")).Copy
Set NewBook = ActiveWorkbook
FileExtStr = ".xlsx": FileFormatNum = 51
With NewBook
.SaveAs Filename:=Fpath & FName2 & "-" & x & FName & ".xlsx"
'.Close False
End With
''''''''''''''''''''''''''''''''''''''''''''
'The section below deletes data from each tab that is not specific to the individual.
Sheets("Variables").Select
' Range("C5").Select
' Selection.Copy
Range("B10").Select
ActiveCell.FormulaR1C1 = x
' Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
' :=False, Transpose:=False
Sheets("Summary").Select
Call Loop_Delete_Summary
Sheets("Data").Select
ActiveSheet.ListObjects(1).Unlist
Call Loop_Delete_Summary
Sheets("Modifier %").Select
ActiveWorkbook.ActiveSheet.ListObjects(1).Unlist
Call Delete_Modifier_Percent
Sheets("Modifier Dollar").Select
ActiveSheet.ListObjects(1).Unlist
Call Loop_Delete_Summary
'Sheets("Controls").Select
Sheets("Variables").Select
ActiveWindow.SelectedSheets.Delete
Call ResetCursor
''''''''''''''''''''''''''''''''''''''''''''
Next i
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
End Sub```
```Sub Loop_Delete_Summary()
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim rng As Range
With ActiveSheet
.Select
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
'Set the first and last row to loop through
Firstrow = .UsedRange.Offset(1).Row
Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
'Loop from Lastrow to Firstrow (bottom to top)
For Lrow = Lastrow To Firstrow Step -1
'Check the values in the A column
With .Cells(Lrow, "A")
If Not IsError(.Value) Then
If .Value <> Worksheets("Variables").Range("B10") Then
If rng Is Nothing Then
Set rng = .Cells
Else
Set rng = Application.Union(rng, .Cells)
End If
End If
End If
End With
Next Lrow
End With
'Delete all rows at once
If Not rng Is Nothing Then rng.EntireRow.Delete
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.Calculation = CalcMode
End With
End Sub```
```Sub Loop_Delete_Modifier_Percent()
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
'We use the ActiveSheet but you can replace this with
'Sheets("MySheet")if you want
With ActiveSheet
'We select the sheet so we can change the window view
.Select
'If you are in Page Break Preview Or Page Layout view go
'back to normal view, we do this for speed
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
'Turn off Page Breaks, we do this for speed
.DisplayPageBreaks = False
'Set the first and last row to loop through
Firstrow = 2
Lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
'We loop from Lastrow to Firstrow (bottom to top)
For Lrow = Lastrow To Firstrow Step -1
'We check the values in the A column in this example
With .Cells(Lrow, "B")
If Not IsError(.Value) Then
Select Case .Value
Case Is <> Worksheets("Variables").Range("B10").Value: .EntireRow.Delete
End Select
End If
End With
Next Lrow
End With
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.Calculation = CalcMode
End With
End Sub```
*****The code when using F8 to step through seems to skip over this section...*****
``` x = Sourcewb.Sheets(1).Range("A" & i).Value
Sourcewb.Sheets(Array("Summary", "Pivot", "Data", "Modifier %", "Modifier Dollar", "Variables")).Copy
Set NewBook = ActiveWorkbook
FileExtStr = ".xlsx": FileFormatNum = 51
With NewBook
.SaveAs Filename:=Fpath & FName2 & "-" & x & FName & ".xlsx"
'.Close False
End With
Sheets("Variables").Select
' Range("C5").Select
' Selection.Copy
Range("B10").Select
ActiveCell.FormulaR1C1 = x
' Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
' :=False, Transpose:=False
Sheets("Summary").Select
Call Loop_Delete_Summary
Sheets("Data").Select
ActiveSheet.ListObjects(1).Unlist
Call Loop_Delete_Summary
Sheets("Modifier %").Select
ActiveWorkbook.ActiveSheet.ListObjects(1).Unlist
Call Delete_Modifier_Percent
Sheets("Modifier Dollar").Select
ActiveSheet.ListObjects(1).Unlist
Call Loop_Delete_Summary
'Sheets("Controls").Select
Sheets("Variables").Select
ActiveWindow.SelectedSheets.Delete
Call ResetCursor
Next i```
It appears that the order of the tabs was the issue. I noticed that Lastrow = Sourcewb.Sheets(1).Cells(Sourcewb.Sheets(1).Rows.Count, "A").End(xlUp).Row
Lastrow = 0.
I moved the front 2 tabs which had no data to the end of the tabs and it works.
Otherwise, for whatever reason, it would find zero as the last row and simply skip to the end.

Filter workbook and copy range into another workbook at next available cell

I want to filter workbook by looking for all blank entries in column E. Then copy range into another workbook at the next available row. When I run my code I get an error 'run time error' 1004 - PasteSpecial method of range class failed?? How would I debug this to be able to copy my range and paste into other workbook?
I have only just started learning VBA and learned most of what I know from google and watching youtube videos. I have tried to change the value for blank "", I have tried to add application.cutcopymode false
Sub MoveUnworkedtoDB()
`Dim wbk As Workbook
Dim sh As Worksheet
Dim Lastrow As Long
' Open worksheet 1 and move unworked back to database
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Set wbk = Workbooks.Open(Filename:= _
"Workbook1")
Set sh = wbk.Sheets("sheet1")
'Clear any existing filters
On Error Resume Next
sh.ShowAllData
On Error GoTo 0
'Apply Filter
sh.Range("A1:E9").AutoFilter Field:=5, Criteria1:=""
'copy Range
Application.DisplayAlerts = False
sh.Range("B2:e1000").SpecialCells(xlCellTypeVisible).Copy
Application.DisplayAlerts = True
'Clear Filter
On Error Resume Next
sh.ShowAllData
On Error GoTo 0
Set wbk = Workbooks.Open(Filename:= _
"workbook2")
Set sh = wbk.Sheets("sheet1")
Lastrow = Range("A65536").End(xlUp).row
Sheets("sheet1").Activate
Cells(Lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues,
Operation:=xlNone, _
SkipBlanks:=False, Transpose:=True
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
End Sub`
runtime error 1004 - pastespecial method of range class failed
Depends on Excel version. You can't do this in Excel 2003 and older. You transpose 1000 rows to 1000 columns, old Excels have 256 columns only.
I corrected a bit Your code, now will work in newest versions, from 2007 up.
Sub MoveUnworkedtoDB()
Dim wbk As Workbook
Dim sh As Worksheet
Dim Lastrow As Long
Dim wbk2 As Workbook
Dim sh2 As Worksheet
' Open worksheet 1 and move unworked back to database
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Set wbk = Workbooks.Open(Filename:="C:\temp\A.xlsx")
Set sh = wbk.Sheets(1)
'Clear any existing filters
On Error Resume Next
sh.ShowAllData
On Error GoTo 0
'Apply Filter
sh.Range("A1:E9").AutoFilter Field:=5, Criteria1:=""
'copy Range
Application.DisplayAlerts = False
'sh.Range("B2:e1000").SpecialCells(xlCellTypeVisible).Copy
Application.DisplayAlerts = True
'Clear Filter
On Error Resume Next
sh.ShowAllData
On Error GoTo 0
Set wbk2 = Workbooks.Open(Filename:="C:\temp\B.xlsx")
Set sh2 = wbk2.Sheets(1)
With sh2
Lastrow = .Range("A65536").End(xlUp).Row
sh.Range("B2:e1000").SpecialCells(xlCellTypeVisible).Copy
.Cells(Lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
End Sub

Resources