VBA Excel - Delete - Cannot use that command on overlapping selections - excel

I am trying to apply filter to the data and copy the filtered data to an other sheet and delete the filtered rows in base sheet.
I am facing error as 'cannot use the command on overlapping selection'
When I try to delete the filtered rows in base sheet using
specialcells(xlcelltypevisible).entirerow.delete
Sheets("analysis").select
Sourcecol=1
VCurrLength = cells(rows.count, sourcecol).end(clip).row
Activesheet.range("$A$1:$W$"& VCurrLength).autofilter field:=7, criteria1:= "ZP"
Range ("A1").select
Selection.end(xldown).select
If selection.row<1000000 then
Range("A2:w"& VCurrLength).specialcells(xlcelltypevisible).copy
Sheets("temp").select
Activesheet.paste
Sheets("analysis").select
Range("A2:w"& VCurrLength).specialcells(xlcelltypevisible).select
Selection.entirerow.delete
Endif

Backup Data
Option Explicit
Sub backupData()
Dim Success As Boolean
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets("analysis")
Dim sLR As Long: sLR = sws.Cells(sws.Rows.Count, "A").End(xlUp).Row
Dim srg As Range: Set srg = sws.Range("A1:W" & sLR)
Application.ScreenUpdating = False
If sws.AutoFilterMode Then
sws.AutoFilterMode = False
End If
srg.AutoFilter field:=7, Criteria1:="ZP"
If WorksheetFunction.Subtotal(103, srg.Cells.Resize(, 1)) > 1 Then
Dim dws As Worksheet: Set dws = wb.Worksheets("temp")
Dim dcell As Range
Set dcell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
Dim frg As Range
Set frg = srg.Resize(srg.Rows.Count - 1).Offset(1) _
.SpecialCells(xlCellTypeVisible)
frg.Copy dcell
frg.EntireRow.Delete
If Not sws Is ActiveSheet Then
sws.Activate
End If
srg.Cells(1).Select
Success = True
End If
sws.AutoFilterMode = False
Application.ScreenUpdating = True
If Success Then
MsgBox "Data updated.", vbInformation, "Success"
Else
MsgBox "No updates available.", vbExclamation, "Nope"
End If
End Sub

Related

Problems with pasting while shifting down cells

Hi I am trying to copy info from a workbook into another workbook and paste while shifting cells down.
My problem is that is not pasting the information at all. The code does everything is supposed to except for pasting the rows.
Sub filter_copy_paste()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim whatToFind As String
Dim foundTwo As Range
Dim newSelectionRange As Range
Dim rowSelectionRange As Range
Dim Found_Row As Long
Dim num As Integer
'
Sheets("Sheet1").Select
whatToFind = "Mean"
Set foundTwo = Cells.Find(What:=whatToFind, After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'
Found_Row = foundTwo.row
With Sheets("Main").Range("A12:S12").CurrentRegion
.AutoFilter Field:=19, Criteria1:="Yes"
.SpecialCells(xlCellTypeVisible).EntireRow.Copy
'_
' Destination:=Sheets("Sheet1").Range("A1")
'
' I added the following line to insert selection and shift down in Cells above mean
'
Set rowSelectionRange = Rows(Found_Row - 1).Resize(1)
rowSelectionRange.Select
Selection.Insert Shift:=xlDown
End With
'
'Following is added to clean up my previous worksheet
'
Sheets("Main").Select
If ActiveSheet.FilterMode = True Then
ActiveSheet.ShowAllData
End If
Sheets("Main").Select
Rows("3:11").Select
Range("A11").Activate
Selection.EntireRow.Hidden = True
Application.CutCopyMode = False
Sheets("Sheet1").Select
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I am expecting the copied rows to be inserted in the range above Mean
This should do what you need:
Sub filter_copy_paste()
Const FIND_THIS As String = "mean" 'use const for fixed values
Dim f As Range, numRows As Long, wsSrc As Worksheet, wsDest As Worksheet
Set wsSrc = ThisWorkbook.Worksheets("Main") 'source table
Set wsDest = ThisWorkbook.Worksheets("Sheet2") 'copy to here
Set f = wsDest.Cells.Find(What:=FIND_THIS, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If f Is Nothing Then
MsgBox "'" & FIND_THIS & "' not found on " & wsDest.Name, vbExclamation
Exit Sub
End If
With wsSrc.Range("A12:S12").CurrentRegion
Debug.Print "Data", .Address()
.AutoFilter Field:=19, Criteria1:="Yes"
'how many rows will be copied?
numRows = .Columns(1).SpecialCells(xlCellTypeVisible).Count
f.Resize(numRows).EntireRow.Insert shift:=xlDown 'insert the rows
'copy visible rows
.SpecialCells(xlCellTypeVisible).Copy wsDest.Cells(f.Row - numRows, "A")
End With
wsSrc.ShowAllData
End Sub
Insert Filtered Rows
Sub InsertFilteredRows()
Application.ScreenUpdating = False
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Source
Dim sws As Worksheet: Set sws = wb.Sheets("Main")
If sws.FilterMode Then sws.ShowAllData
If sws.AutoFilterMode Then sws.AutoFilterMode = False
Dim srg As Range: Set srg = sws.Range("A12").CurrentRegion
srg.AutoFilter Field:=19, Criteria1:="Yes"
Dim svrg As Range: Set svrg = srg.SpecialCells(xlCellTypeVisible)
sws.AutoFilterMode = False
Dim sarg As Range, srCount As Long
For Each sarg In svrg.Areas: srCount = srCount + sarg.Rows.Count: Next sarg
'Debug.Print srg.Address, svrg.Address, srCount
' Destination
Dim dws As Worksheet: Set dws = wb.Sheets("Sheet1")
If dws.FilterMode Then dws.ShowAllData
Dim durg As Range: Set durg = dws.UsedRange
Dim dlCell As Range: Set dlCell = durg.Cells(durg.Cells.CountLarge)
' Starting with the first cell of the used range searching by rows,
' attempt to find the first cell that contains the search string.
' The search is by default case-insensitive ('A=a').
Dim dfCell As Range: Set dfCell = dws.Cells.Find( _
What:="Mean", After:=dlCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows) ' the rest are default parameters
If dfCell Is Nothing Then Exit Sub ' string not found
Dim dirg As Range: Set dirg = Intersect(durg, dfCell.EntireRow) _
.Resize(srCount) ' your code additionally suggests '.Offset(-1)' !?
'Debug.Print svrg.Address, dfCell.Address, dirg.Address
' Insert and copy.
dirg.Insert Shift:=xlShiftDown
' Cannot determine the 'CopyOrigin' parameter without seeing the data.
' Copy.
svrg.Copy dirg.Columns(1).Offset(-srCount)
' Clean up!?
sws.Rows("3:11").Hidden = True
If Not wb Is ActiveWorkbook Then wb.Activate
dws.Select
Application.ScreenUpdating = True
' Inform.
MsgBox "Filtered rows inserted.", vbInformation
End Sub

Paste Special breaking VBA Module

I have been trying to figure out why I am not able to paste values only in this VBA module. Can anyone spot my issue? I have tried many different combinations, and still getting compile errors
Sub Merge_Sheets()
'Set Master sheet for consolidation
Set mtr = Worksheets("Master")
Set wb = ThisWorkbook
'loop through all sheets
For Each ws In wb.Worksheets
'except the master sheet from looping
If ws.Name <> "Master" Then
ws.Activate
Range("A5:P20").Copy _
mtr.Range("A" & mtr.Cells(Rows.Count, 1).End(xlUp).Row + 1).PasteSpecial xlPasteValues
End If
Next ws
Worksheets("Master").Activate
End Sub
Does anyone have any ideas for the issue on this? Thanks in advance!
Append Range Values From All Worksheets
Option Explicit
Sub AppendRangeValues()
Const SRC_RANGE As String = "A5:P20"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = wb.Sheets("Master")
Dim dfCell As Range
Set dfCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
Dim drg As Range, rCount As Long
With dws.Range(SRC_RANGE)
rCount = .Rows.Count
Set drg = dfCell.Resize(rCount, .Columns.Count)
End With
Dim sws As Worksheet
For Each sws In wb.Worksheets
If Not sws Is dws Then
drg.Value = sws.Range(SRC_RANGE).Value
Set drg = drg.Offset(rCount)
End If
Next sws
MsgBox "Range values appended.", vbInformation
End Sub

VBA Copy data from the file I select to the next empty row

I am trying to get data to be copy over to the next empty row. I have data starting in Cell A6. Can you please advise why my Lastrow2 is giving me an error and not copying the data to next empty row?
Dim FTO As Variant
Dim OB As Workbook
Dim Lastrow2 As Long
Lastrow2 = .Cells(.Rows.Count, "A").End(xlUp).Offset(-1).Row
Application.ScreenUpdating = False
FTO = Application.GetOpenFilename(Title:="Browse for your File & Import", FileFilter:="Excel Files (*.xls*), *xls*")
If FTO <> False Then
Set OB = Application.Workbooks.Open(FTO)
OB.Sheets(1).Range("E4:BW100").Copy
ThisWorkbook.Worksheets("Master").Range("A6" & Lastrow2).PasteSpecial xlPasteValues
OB.Close False
End If
Application.ScreenUpdating = True
I have tried modifying the lastrow function using the following code. Can I use the piece below to work on the function?
Lastrow2 = ThisWorkbook.Sheets(1).Range("A6").End(xlDown).Row + 1
Range(Selection, Selection.End(xlDown)).Select
If FTO <> False Then
Set OB = Application.Workbooks.Open(FTO)
OB.Sheets(1).Range("E4:BW100").Copy
ThisWorkbook.Worksheets("Master").Range("A6" & Lastrow2).PasteSpecial xlPasteValues
OB.Close False
End If
Application.ScreenUpdating = True
Copy Values From a Closed Workbook
The Issue
The expression LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Offset(-1).Row is wrong because of the -1 and could only work in a With statement:
Dim FirstRow As Long
With ThisWorkbook.Sheets("Master")
FirstRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Row
End With
or, if you need the first cell
Dim FirstCell As Range
With ThisWorkbook.Sheets("Master")
Set FirstCell = .Cells(.Rows.Count, "A").End(xlUp).Offset(1)
End With
These leading dots tell us that these cells or rows are located in the worksheet Master in the workbook containing this code (ThisWorkbook).
An Improvement
Sub CopyValues()
' Define constants.
' The Source workbook will be opened using 'Application.GetOpenFilename'.
Const SRC_WORKSHEET_INDEX As Long = 1
Const SRC_RANGE As String = "E4:BW100"
' The Destination workbook is the workbook containing this code.
Const DST_WORKSHEET_NAME As String = "Master"
Const DST_COLUMN As String = "A"
Application.ScreenUpdating = False
' Open the Source file (or not).
Dim SourcePath: SourcePath = Application.GetOpenFilename( _
Title:="Browse for your File & Import", _
FileFilter:="Excel Files (*.xls*), *xls*")
If VarType(SourcePath) = vbBoolean Then Exit Sub ' i.e. 'False'
' Reference the Source range.
Dim swb As Workbook: Set swb = Workbooks.Open(SourcePath)
Dim sws As Worksheet: Set sws = swb.Worksheets(SRC_WORKSHEET_INDEX)
Dim srg As Range: Set srg = sws.Range(SRC_RANGE)
' Reference the Destination range.
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Sheets(DST_WORKSHEET_NAME)
Dim dfCell As Range
Set dfCell = dws.Cells(dws.Rows.Count, DST_COLUMN).End(xlUp).Offset(1)
Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
' Copy values.
drg.Value = srg.Value
' Close the Source file.
swb.Close False
Application.ScreenUpdating = True
End Sub

Copy range of cells from one workbook to another

How can a range of cells be copied from one workbook to another? The code below does not work. I believe there is something wrong with how the range of cells are selected: sht1.Range("A1:D1").Select
Sub ImportData()
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Application.ScreenUpdating = False
Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open("C:\Users\Temp\Desktop\MyExcelSheet.xlsm")
Set sht1 = wkb1.Sheets("Data")
Set sht2 = wkb2.Sheets("Summary")
'Function to clear the existing data. Doesn't work.
sht1.Range("A1:D1").Select
sht1.Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
' Copies data from the "Summary" sheet.
sht2.Range("O6:P102").Copy
sht2.Range("O6").Select
sht2.Range(Selection, Selection.End(xlToRight)).Select
sht2.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy ' Copies all of the highlighted cells.
sht1.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True
Application.ScreenUpdating = True
MsgBox "Complete"
End Sub
Replace:
sht1.Range("A1:D1").Select
sht1.Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
With
sht1.Range("A1:D" & Range("D1").End(xlDown).Row).Clear
Unless you specifically want to manually highlight the cells and then run the macro, this solution works.
This replacement code will now highlight every cell between "A1:D1" however, XlDown is only applied on the column "D".
Copy the Values of a Range
Option Explicit
Sub ImportData()
' Source (open, read from & close)
Const sFilePath As String = "C:\Users\Temp\Desktop\MyExcelSheet.xlsm"
Const sName As String = "Summary"
Const sFirstRowAddress As String = "O6:R6"
' Destination (write to & save)
Const dName As String = "Data"
Const dFirstCellAddress As String = "A1"
' Source
Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)
Dim sws As Worksheet: Set sws = swb.Worksheets(sName)
Dim srg As Range
With sws.Range(sFirstRowAddress)
Dim lCell As Range: Set lCell = .Resize(sws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If lCell Is Nothing Then
MsgBox "No data found.", vbCritical
Exit Sub
End If
Set srg = .Resize(lCell.Row - .Row + 1)
End With
' Destination
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
' Clear & copy.
With dws.Range(dFirstCellAddress).Resize(, srg.Columns.Count)
' Clear previous data.
.Resize(dws.Rows.Count - .Row + 1).Clear
' Copy values by assignment.
.Resize(srg.Rows.Count).Value = srg.Value
End With
' Save & close.
swb.Close SaveChanges:=False
'dwb.Save
' Inform.
MsgBox "Values copied.", vbInformation
End Sub

Not copying data after column Z

I've got a spreadsheet with data from column A:AA. I'm trying to copy over all of the data from sheet CycleCountResearch in "workbook-a" to CycleCountResearch sheet in "workbook-b". All of the data except for column AA copy's over. Column AA contains the filename, so that when it is copied over from workbook a to workbook b, the user can look at the data in workbook b and know which file the data came from. Is there any recommendation on how to fix column AA not copying over?
Here is the code so far:
Sub Export()
Dim FileName As String
FileName = "\\InventoryControlDatabase\DoNotOpen\DoNotOpenDCAtest.xlsx"
'Call function to check if the file is open
If IsFileOpen(FileName) = False Then
Application.ScreenUpdating = False
Worksheets("CycleCountResearch").Unprotect "123"
Dim LR As Long
Dim src As Workbook
LR = Worksheets("CycleCountResearch").Cells(Rows.Count, "B").End(xlUp).Row
Set src = Workbooks.Open("\\InventoryControlDatabase\DoNotOpen\DoNotOpenDCAtest.xlsx")
ThisWorkbook.Worksheets("CycleCountResearch").AutoFilterMode = False
ThisWorkbook.Worksheets("CycleCountResearch").Range("A4:AA" & LR).AutoFilter Field:=23, Criteria1:="Done", _
Operator:=xlFilterValues
On Error Resume Next
ThisWorkbook.Worksheets("CycleCountResearch").Range("A5:AA" & LR).SpecialCells(xlCellTypeVisible).Copy
src.Activate
src.Worksheets("CycleCountResearch").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
'src.Worksheets("CycleCountCompleted").UsedRange.RemoveDuplicates Columns:=1, Header:=xlYes
Workbooks("DoNotOpenDCA.xlsx").Close SaveChanges:=True
Application.ScreenUpdating = True
Call UpdateMasterLog
Call ClearUpdates
ThisWorkbook.Worksheets("CycleCountResearch").Range("K2:K2").ClearContents
'Clears the name of the user editing the sheet
Else
MsgBox "Someone else is saving. Please wait a moment and try again"
Exit Sub
End If
End Sub
Backup Data
This is how I see it. Read through it before running it because you may have to rearrange some lines in the Finishing Touches part (e.g. ClearUpdates, UpdateMasterLogs).
The best advice from it should be about using variables. They will not slow down the code but will make it more readable, the obvious example being the variables srg, sdrg, and sdfrg.
Option Explicit
Sub ExportData()
Const dFilePath As String _
= "\\InventoryControlDatabase\DoNotOpen\DoNotOpenDCAtest.xlsx"
'Call function to check if the file is open
If Not IsFileOpen(dFilePath) Then ' source workbook is closed
Application.ScreenUpdating = False
' Source
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets("CycleCountResearch")
sws.Unprotect "123"
sws.AutoFilterMode = False
Dim slRow As Long: slRow = sws.Range("B" & sws.Rows.Count).End(xlUp).Row
' Source Range (has headers)
Dim srg As Range: Set srg = sws.Range("A4:AA" & slRow)
srg.AutoFilter Field:=23, Criteria1:="Done" ' '23' is 'W'
' Source Data Range (no headers)
Dim sdrg As Range: Set sdrg = srg.Resize(srg.Rows.Count - 1).Offset(1)
' Source Data Filtered Range
Dim sdfrg As Range
On Error Resume Next ' prevent error if no cells
Set sdfrg = sdrg.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not sdfrg Is Nothing Then
' Destination
Dim dwb As Workbook: Set dwb = Workbooks.Open(dFilePath)
Dim dws As Worksheet: Set dws = dwb.Worksheets("CycleCountResearch")
Dim dCell As Range
Set dCell = dws.Range("A" & dws.Rows.Count).End(xlUp).Offset(1)
sdfrg.Copy¸
dCell.PasteSpecial Paste:=xlPasteValues
'dwb.Worksheets("CycleCountCompleted").UsedRange.RemoveDuplicates _
Columns:=1, Header:=xlYes
dwb.Close SaveChanges:=True
' Finishing Touches
UpdateMasterLog
ClearUpdates
'Clear the name of the user editing the sheet
sws.Range("K2:K2").ClearContents
sws.AutoFilterMode = False
sws.Protect "123"
Application.ScreenUpdating = True '
MsgBox "Data exported.", vbInformation
Else ' no filtered data
sws.AutoFilterMode = False
MsgBox "No filtered data.", vbCritical
'Exit Sub
End If
Else ' source workbook is open
MsgBox "Someone else is saving. Please, try again later.", vbExclamation
'Exit Sub
End If
End Sub

Resources