Not copying the values properly - vba

I have a problem with my macro to copy paste only the values of the range A6:AM46,A52:AM84 to AN6 location on the same sheet.
Sub PréparerGrilles()
Range("A6:AM46,A52:AM84").Select
Selection.Copy
Range("AN6").Select
Application.CutCopyMode = False
ActiveSheet.Paste
End Sub
I get the 1004 error (multiple selection error)
Could you help me with this ?

To copy values from A6:AM46,A52:AM84 to AN6:BZ46,AN52:BZ84 you can do the following:
Sub PreparerGrilles()
Range("AN6:BZ46").Value = Range("A6:AM46").Value
Range("AN52:BZ84").Value = Range("A52:AM84").Value
End Sub
Version using the Range.Copy method:
Sub PreparerGrilles()
Range("A6:AM46").Copy Destination:=Range("AN6:BZ46")
Range("A52:AM84").Copy Destination:=Range("AN52:BZ84")
Range("AN6:BZ46").Value = Range("AN6:BZ46").Value
Range("AN52:BZ84").Value = Range("AN52:BZ84").Value
End Sub
I recommend that you don't slow your code down by using this. It will also lead to potentially incorrect values if your formulae refer to anything that wasn't part of the copy.
Version using a PasteSpecial xlPasteValues method:
Sub PreparerGrilles()
Range("A6:AM46").Copy
Range("AN6:BZ46").PasteSpecial xlPasteValues
Range("A52:AM84").Copy
Range("AN52:BZ84").PasteSpecial xlPasteValues
End Sub
I strongly recommend against using this method, as it leads to too many "unreproducible" errors due to the users copying things via the clipboard between when your code does the Copy and when it does the Paste, and also because of the fact that your Copy zaps whatever the user might have manually pasted to the clipboard.

Application.CutCopyMode = False cleans the clipboard....
Better code for that is:
Sub Test()
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("SOMMAIRE") 'this means it will only work on this sheet, you should change the name of the sheet or ask me what do you want in order to get it working on other sheets
ws.Range("A6:AL46").Copy
ws.Range("AN6").PasteSpecial xlValues
ws.Range("A52:AM84").Copy
ws.Range("AN52").PasteSpecial xlValues
End Sub
Edited: Now that should do the trick. Try it out and tell me if it works
Edited2: This is what you want, at least for what you asked so far.

Related

How to copy a whole sheet and transpose paste into another sheet in VBA?

Working environment:Excel 2013.
Target:
copy a whole sheet
create another sheet
transpose paste the copied sheet into this new sheet.
the code that i am using is as below:
Worksheets("Sheet4").Copy
Worksheets("Master").PasteSpecial Transpose:=True
however when i run it, i got an error
application defined or object defined error
Anyone can help me to figure out why?
Maybe you after something like the code below:
Option Explicit
Sub CreateAndCopyTran()
Dim ws As Worksheet
' create a new worksheet, and name it "Master"
Set ws = ThisWorkbook.Worksheets.Add(after:=ThisWorkbook.Worksheets(1))
ws.Name = "Master"
' copy the UsedRange and Transpose
Worksheets("Sheet4").UsedRange.Copy
ws.Range("A1").PasteSpecial xlPasteAll, Transpose:=True
End Sub
You want to copy the cells in Sheet4, not the sheet itself, so you need to call the copy method of a range/cells.
Similarly, the PasteSpecial method needs to be called on a range object, rather than a sheet object.
You could try this, for example:
Sub test()
Worksheets("Sheet4").UsedRange.Copy
Worksheets("Master").Cells(1, 1).PasteSpecial Transpose:=True
End Sub

Copy Paste Across Worksheets (VBA)

I don't know why, I just can't get this to work. I've simplified it right down to just three lines - but it's causing me problems still.
Basically I want to open a workbook and copy some data from it into a master workbook.
I have:
Sub copypaste()
Workbooks.Open("...Test.xlsx").Sheets("Sheet1").Cells(1, 1).Copy
ActiveWorkbook.Close
Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
End Sub
I've seen runtime error 438 (object does not support this property method), I can get paste that but just hit 1004 application defined error or object defined error.
I honestly have no idea where I'm going wrong on this simple task!
Thank you in advance,
Tom
Try closing the workbook after pasting the data.
As an example you can use something like:
Sub copypaste()
Dim WBopen As Workbook, Wb As Workbook
Set Wb = ActiveWorkbook
Set WBopen = Workbooks.Open("...Test.xlsx")
WBopen.Sheets("Sheet1").Cells(1, 1).Copy
Wb.Sheets("Sheet1").Range("A1").PasteSpecial xlPasteValues
WBopen.Close
End Sub
Because you are closing the Workbook before the data is pasted it fails.
It is also preferred to not use .Copy and .Paste when it can be avoided.
See example below for a direct setting of the Values:
Sub copypaste()
Dim wbMaster As Workbook, wbData As Workbook
Set wbMaster = Workbooks("Master.xlsm")
Set wbData = Workbooks.Open("Data.xlsx")
wbMaster.Sheets("Sheet1").Range("A1").Value = wbData.Sheets("Sheet1").Range("A1").Value
wbData.Close False
End Sub

Copy cell values over to new worksheet but not the formatting

I am trying to copy over the cell values and contents over to a new, locked worksheet, but currently the code is bringing over the original worksheet's formatting. Currently the code I am using is:
Sub sbCopyRangeToAnotherSheet()
Sheets("LTL Quote Form").Range("A1:L33").Copy Destination:=Sheets("Sheet3").Range("A1")
Application.CutCopyMode = False
End Sub
And I've even tried:
Sub Copy()
Sheets("LTL Quote Form").Range("A5:L11").Copy
Sheets("Sheet1").Range("A5:L11").PasteSpecial xlPasteValues
End Sub
But neither of them are working. Any suggestions on how to copy over the cell values, but not the formatting?
The second example you posted will paste values, not formatting. You could also use:
Sub sbCopyRangeToAnotherSheet()
Sheets("Sheet3").Range("A1:L33").Value2 = Sheets("LTL Quote Form").Range("A1:L33").Value2
End Sub

Create an IF statement to check and remove the advanced filter [duplicate]

It seems older macros are not working. I have proper securtiy set to run VBA macros but when I have tried a few methods for clearing ALL filters on a worksheet, I get a compile error.
Here is what I have tried:
Sub AutoFilter_Remove()
'This macro removes any filtering in order to display all of the data but it does not remove the filter arrows
ActiveSheet.ShowAllData
End Sub
I have buttons on the sheets to clear all filters for ease of use for users since the sheets has a lot of columns that have filters on them.
Try this:
If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData
ShowAllData will throw an error if a filter isn't currently applied. This will work:
Sub ResetFilters()
On Error Resume Next
ActiveSheet.ShowAllData
End Sub
If the sheet already has a filter on it then:
Sub Macro1()
Cells.AutoFilter
End Sub
will remove it.
For tables try this to check if it's on and turn off:
If wrkSheetCodeName.ListObjects("TableName").ShowAutoFilter Then
wrkSheetCodeName.ListObjects("TableName").Range.AutoFilter
End if
To Turn back on:
wrkSheetCodeName.ListObjects("TableName").Range.AutoFilter
this works nice.!
If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
That is brilliant, the only answer I found that met my particular need, thanks SO much for putting it up!
I made just a minor addition to it so that the screen didn't flash and it removes and subsequently reapplies the password on each sheet as it cycles through [I have the same password for all sheets in the workbook]. In the spirit of your submission, I add this to assist anyone else....
Sub ClearFilters()
Application.ScreenUpdating = False
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
'Change the password to whatever is required
wrksheet.Unprotect Password:="Albuterol1"
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
'Change the password to whatever is required
wrksheet.Protect Password:="Albuterol1", _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True, _
AllowFiltering:=True
Next 'Check next worksheet in the workbook
Next
Application.ScreenUpdating = True
End Sub
I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..
Hopefully this helps someone out there :)
Sub ResetFilters()
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
Next 'Check next worksheet in the workbook
Next
End Sub
There are two types of filters in Excel:
Auto Filter
Advanced Filter
The Auto Filter feature lets you filter from the excel interface using those tiny dropdown buttons. And the Advanced filter feature lets you filter using a criteria range.
The ShowAll method removes the filters, as in, shows all the rows, but does not get rid of those Drop Down buttons. You have to set the AutoFilterMode property of the worksheet to FALSE to remove those buttons.
Here is a Sub that I use frequently to remove filters:
Sub RemoveFilters(ByRef WhichSheet As Worksheet)
If WhichSheet.FilterMode Then WhichSheet.ShowAllData
If WhichSheet.AutoFilterMode Then WhichSheet.AutoFilterMode = False
End Sub
This shows all the data, and removes the dropdown buttons. It comes in handy while stacking (copying and pasting) data from multiple sheets or workbooks. Hope this helps.
I found this workaround to work pretty effectively. It basically removes autofilter from the table and then re-applies it, thus removing any previous filters. From my experience this is not prone to the error handling required with the other methods mentioned here.
Set myTable = YOUR_SHEET.ListObjects("YourTableName")
myTable.ShowAutoFilter = False
myTable.ShowAutoFilter = True
This will work too:
If ActiveSheet.FilterMode Then cells.AutoFilter
I usually use this code
Sub AutoFilter_Remove()
Sheet1.AutoFilterMode = False 'Change Sheet1 to the relevant sheet
'Alternatively: Worksheets("[Your Sheet Name]").AutoFilterMode = False
End Sub
This will first check if AutoFilterMode is set (filtering is possible), then check if FilterMode is on (you are filtering on something) then turn off filtering.
Regarding Errors, i.e. protection - se other answers
Context added (my script is looping over sheets, which are then saved as CSV, hence the need to remove filters - but keep AutoFilterMode on, if set:
For Each WS In ActiveWorkbook.Worksheets
Select Case WS.Name
Case "01", "02", "03", "04", "05"
With WS
If WS.AutoFilterMode Then
If WS.FilterMode Then WS.ShowAllData
End If
' Processing data
End With
Case Else
' Nothing to see here
End Select
Next
Try something like this:
Sub ClearDataFilters()
'Clears filters on the activesheet. Will not clear filters if the sheet is protected.
On Error GoTo Protection
If ActiveWorkbook.ActiveSheet.FilterMode Or _
ActiveWorkbook.ActiveSheet.AutoFilterMode Then _
ActiveWorkbook.ActiveSheet.ShowAllData
Exit Sub
Protection:
If Err.Number = 1004 And Err.Description = _
"ShowAllData method of Worksheet class failed" Then
MsgBox "Unable to Clear Filters. This could be due to protection on the sheet.", _
vbInformation
End If
End Sub
.FilterMode returns true if the worksheet is in filter mode. (See this for more information.)
See this for more information on .AutoFilter.
And finally, this will provide more information about the .ShowAllData method.
Here's the one-liner I use. It checks for an auto-filter and if found, removes it.
Unlike some answers, this code won't create an auto-filter if used on a worksheet that is not auto-filtered in the first place.
If Cells.AutoFilter Then Cells.AutoFilter
All you need is:
ActiveSheet.AutoFilter.ShowAllData
Why? Like the worksheet, AutoFilter also has a ShowAllData method, but it doesn't throw an error even when auto filter is enabled without an active filter.
This works best for me.
I usually use the following before I save and close the files.
Sub remove_filters
ActiveSheet.AutofilterMode = False
End Sub
Simply activate the filter headers and run showalldata, works 100%. Something like:
Range("A1:Z1").Activate
ActiveSheet.ShowAllData
Range("R1:Y1").Activate
ActiveSheet.ShowAllData
If you have the field headers in A1:Z1 and R1:Y1 respectively.
Im using .filtermode if filter is on it returns true
Dim returnValue As Boolean
returnValue = worksheet1.FilterMode
if returnValue Then
worksheet1.ShowAllData
End If
Try this:
Sub ResetFilters()
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
For Each ws In ActiveWorkbook.Worksheets
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next ws
End Sub
This Code clears all filters and removes sorting.
Source: Removing Filters for Each Table in a Workbook, VBA
Here is some code for fixing filters. For example, if you turn on filters in your sheet, then you add a column, then you want the new column to also be covered by a filter.
Private Sub AddOrFixFilters()
ActiveSheet.UsedRange.Select
' turn off filters if on, which forces a reset in case some columns weren't covered by the filter
If ActiveSheet.AutoFilterMode Then
Selection.AutoFilter
End If
' turn filters back on, auto-calculating the new columns to filter
Selection.AutoFilter
End Sub
This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:
We start with:
Sub ResetWSFilters(ws as worksheet)
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This gets rid of "normal" filters - but tables will remain filtered
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
'And this gets rid of table filters
End Sub
We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook
Sub ResetAllWBFilters(wb as workbook)
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:
Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub
The one I use the most: Resetting all filters in the workbook that the module is stored in:
Sub ResetFilters()
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
Set wb = ThisWorkbook
'Set wb = ActiveWorkbook
'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
This will clear only if you have filter and does not cause any error when there arent any filter.
If ActiveSheet.AutoFilterMode Then ActiveSheet.Columns("A").AutoFilter
I am using this approach for a multi table and range sheet as a unique way.
Sub RemoveFilters(Ws As Worksheet)
Dim LO As ListObject
On Error Resume Next
Ws.ShowAllData
For Each LO In Ws.ListObjects
LO.ShowAutoFilter = True
LO.AutoFilter.ShowAllData
Next
Ws.ShowAllData
End Sub
Wow. Logging in afterwards deleted all but a portion of the first line. My mistake. However, this will be terse.
For both tests
Enter text in A1 and A5 of Sheet1
Filter for blanks only.
Run either test
Enter text in A5
Try to filter!
Sub SubsequentFilterFails()
With Sheet1 'assumes code name is still Sheet1
.ShowAllData 'assumes a filter has been applied
.Range(.Cells(2, 1), .Cells(7, 1)).EntireRow.Delete
End With
End Sub
Sub SubsequentFilterWorks()
With Sheet1
.Cells.AutoFilter
.Range(.Cells(2, 1), .Cells(7, 1)).EntireRow.Delete
.Cells.AutoFilter
End With
End Sub
Thus, when filters are being cleared in order to clean the worksheet .Cells.AutoFilter will be used.
Loop AutoFilter columns, if column is activated(on) then reset a column filter, you may insert a new criteria after a loop. This code does not remove AutoFilter banner.
Dim iCol as Long
Dim ws as Worksheet
...
For iCol = 1 To ws.AutoFilter.Filters.count
If ws.AutoFilter.Filters(iCol).On Then ws.AutoFilter.Range.AutoFilter Field:=iCol
Next
...
ws.AutoFilter.Range.AutoFilter Field:=4, Criteria1:="AABBCC"
I found this answer in a Microsoft webpage
It uses the AutoFilterMode as a boolean .
If Worksheets("Sheet1").AutoFilterMode Then Selection.AutoFilter
You must select range of the table first before using ActiveSheet.ShowAllData

Splitting up Copy/Paste without using Select

I am writing an Excel macro in VBA. In a certain part of my code, I need to copy and paste one unmerged cell to a merged cell in a separate workbook. Part of this process is repetitive. The most efficient way for me to achieve this is to copy the cell and then Call a separate Sub with the location it will be pasted into. I have written a version using Select that works:
Sub Macro1()
Workbooks("Book1.xlsm").Worksheets("Sheet1").Activate
ActiveSheet.Range("A1").Copy
Call Macro2
End Sub
Sub Macro2()
Workbooks("Protected_JD_Form.xlsx").Worksheets("Cover Page").Activate
ActiveSheet.Range("E46:G46").Select
Selection.PasteSpecial Paste:=xlPasteFormulasAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
End Sub
But I have been trying to move away from Select and this is the code I came up with:
Sub Macro1()
Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("A1").Copy
Call Macro2
End Sub
Sub Macro2()
Workbooks("Protected_JD_Form.xlsx").Worksheets("Cover Page").Range("E46:G46").PasteSpecial xlPasteFormulasAndNumberFormats
End Sub
This code gives me a 'PasteSpecial method of Range class failed' on the only line of Macro 2.
Is there a way to copy the contents of a cell and then Call a separate Sub with the destination and paste method, without using Select?
Edit: I understand that setting the values equal to each other is simpler than copy/paste. However, in this instance, that is not a possibility.
I also understand the pitfalls of merged cells. I get it. Seriously. But I don't have a choice as I am working with a customer's workbook, which can't be changed.
Edit #2: Following a comment from #ExcelHero, I rebooted my computer and ran the macro again. It worked. I have no idea what was going wrong. Regardless, credit to #ExcelHero for recognizing that my code was correct.
Why a second macro?
Anyways, if it's absolutely necessary, you're going to need to edit your second macros slightly.
Sub Macro1()
Dim copyString As String
copyString = Worksheets("Sheet1").Range("A1").Value
Call Macro2(copyString)
End Sub
You'll notice that now Macro2 is called with copyString after it. This means, that you will run Macro2, and do something with whatever value is set to copyString.
Sub Macro2(text As String)
'Workbooks("Protected_JD_Form.xlsx").Worksheets("Cover Page").Range("E46:G46").Value = text
Workbooks("Protected_JD_Form.xlsx").Worksheets("Cover Page").Range("E46:G46").Value = text
End Sub
In this macro, you'll see I added (text as String) to the macro name. This will take some value (from Macro1, the value is the copyString variable), and then use it in the macro. Does that make sense?
Again, I would only do this way if you absolutely need two macros for this copy/pasting. If you can use just one macro, then these can be combined into a few simple lines:
Sub Macro3()
Dim copyString As String
copyString = Worksheets("Sheet1").Range("A1").Value
Workbooks("Protected_JD_Form.xlsx").Worksheets("Cover Page").Range("E46:G46").Value = copyString
End Sub
...or even further, cut out the copyString middleman (as #findwindow mentioned):
Sub macro4()
Workbooks("Protected_JD_Form.xlsx").Worksheets("Cover Page").Range("E46:G46").Value = Worksheets("Sheet1").Range("A1").Value
End Sub
This format worked for me - simply defining your copy range as a range and passing it to the first sub, and then iterating through the loop of declaring subsequent cells as the paste range, and passing that range on to the pasting sub:
Sub copy_paste()
Dim rng As Range
Set rng = Sheets(1).Range("A1")
Call copy_start(rng)
End Sub
Sub copy_start(ByVal copyRange As Range)
Dim rng As Range
copyRange.copy
For i = 1 To 5
Set rng = Sheets(1).Range("B" & i)
Call pasteover(rng)
Next i
Application.CutCopyMode = False
End Sub
Sub pasteover(ByVal pasteRange As Range)
pasteRange.PasteSpecial Paste:=xlPasteFormulasAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
End Sub
The error resulted from the copy/pasting that I was doing while I was editing my code. Because the code I was copying was still on the clipboard, the macro tried to paste that into the cell, causing the error.
Lessons Learned:
Limit use of the clipboard in VBA
When copy/pasting in the coding window, double check to make sure that you are not affecting the existing code