Macro for copying certain cells between excel worksheets - vba

I would like to make a macro which will copy certain cells values marked by user in one sheet to another,but into different cells.
In one worksheet we have data in cells from A1 to D1,my goal is to paste them into second worksheet but to another cells (A2,A4,A6,A8 in my case)
And also when somebody copies for example more than four cells it will also paste them right next (B2,B4,B6,B8 and so on..)
I've managed something like this but it does not work
Sub sbCopyRangeToAnotherSheet()
'Copy the data
Sheets("Arkusz2").Range("A2:D2").Copy
Sheets("Arkusz1").Activate
'Select the target range
Range("A2", "A5", "A8", "A11").Select
'Paste in the target destination
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub

The correct syntax is
Sub sbCopyRangeToAnotherSheet()
Sheets("Arkusz2").Range("A2:D2").Copy
Sheets("Arkusz1").Range("A2,A5,A8,A11").PasteSpecial
Application.CutCopyMode = False
End Sub
or you can even do it in one line:
Sub sbCopyRangeToAnotherSheet()
Sheets("Arkusz2").Range("A2:D2").Copy Sheets("Arkusz1").Range("A2,A5,A8,A11")
End Sub
And I recommend to read: How to avoid using Select in Excel VBA.

Related

Mirroring Sheet1 to Sheet2 for Interior Color only, through VBA

I have a schedule showing a lot of information. I would like to condense this onto a second sheet that displays the fill color only and none of the values.
I want that any fill color changes are automatically copied from sheet1 to sheet2.
I want the code to work with a specific cell range as they differ from both sheets, (Sheet1 is "D8:QP27) & (Sheet2 is B3:QN22) and to get it to mirror at all.
Sheet1 showing all information
Sheet2 showing fill (Interior.Color)
It looks as if you also want to copy the borders (eg the diagonal border of column I), so I would suggest you use PasteSpecial with the option xlPasteFormats. See https://learn.microsoft.com/en-us/office/vba/api/excel.range.pastespecial
With ThisWorkbook
.Worksheets("Sheet1").Range("D8:QP27").Copy
.Worksheets("Sheet2").Range("B3:QN22").PasteSpecial xlPasteFormats
End With
Update: As you are looking for a trigger to copy the format automatically. First step is to create a subroutine:
Sub copyFormat()
Application.ScreenUpdating = False
With ThisWorkbook
.Worksheets("Sheet1").Range("D8:QP27").Copy
.Worksheets("Sheet2").Range("B3:QN22").PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
Application.ScreenUpdating = True
End Sub
Now you need to find a way to call the code, eg
o call the routine from the Worksheet_SelectionChange-event (drawback: as this is rather slow, it could annoy the user)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
copyFormat
End Sub
o Place a button on the sheet to call the routine.
o Use a Timer to call the routine every n seconds (see https://learn.microsoft.com/en-us/office/vba/api/excel.application.ontime). Plenty of examples on SO and elsewhere

VBA Code works differently in different workbooks

Hello I have a simple VBA code, which copies a column and pastes it in another column without the empty cells, which are in the original column. It works in the woorkbook, where I wrote it. But I copied it to another one, where I need it. It copies the the needed cells more than once and it fills the whole column the these values.
Range("f5:f2500").ClearContents
With Range("d5:d2500")
.Offset(, 0).SpecialCells(xlCellTypeFormulas, _
xlNumbers).Copy
.Offset(, 2).PasteSpecial skipblanks:=True, _
Paste:=xlPasteValues
End With
The Sub below will copy the formulas (with values in cells) from column D, and paste their values in column F, starting from Cell "F5" and down (without blanks).
The Sub receives the Worksheet.Name as an argument, so all the Ranges inside are fully qualified with that certain worksheet's name.
Code
Option Explicit
Sub CopyColumnWOBlanks(wsName As String)
With Worksheets(wsName)
.Range("F5:F" & .Cells(.Rows.Count, "F").End(xlUp).Row).ClearContents
.Range("D5:D" & .Cells(.Rows.Count, "D").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlNumbers).Copy
.Range("F5").PasteSpecial Paste:=xlPasteValues, skipblanks:=True
End With
End Sub
This Main sub below, is just for testing, modify it to fit your needs.
Sub Main()
CopyColumnWOBlanks ("Sheet5") ' <-- change "Sheet5" to whatever worksheet you want the macro to run
End Sub

Data Validation Dynamic Range Moves Range Instead of Expanding Range

In Excel, I have a Data Validated range using the OFFSET() function that I'm hoping to dynamically add information to that I can then select in a drop down list. I have a VBA macro that I'm adding information to this list from and instead of expanding the list from $L$10:$L$230 to $L$10:$L$231, it shifts my list down to $L$11:$L$230. What am I doing incorrectly in my Named Range or Data Validation to not make this work? Or does it have something with using VBA to add to the range that causes it to work incorrectly?
"Rooms" in my Name Manager Refers To:
=OFFSET(Sheet1!$L$10,0,0,COUNTA(Sheet1!$L:$L),1)
My Data Validation Drop Down Souce:
=Rooms
My "insert" Macro to add to the list:
Sub insert()
'
' insert Macro
'
'
Range("A2:E2").Select
Selection.Copy
Sheets("Sheet1").Select
Range("L10:P10").Select
Selection.insert Shift:=xlDown
Sheets("INSERT NEW ROOM").Select
ActiveWindow.SmallScroll Down:=-18
Range("A2").Select
End Sub
I also have a "Sort" VBA included in my Sheet1 for every time a new instance is added from the "INSERT NEW ROOM" tab.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not Intersect(Target, Range("L9:L500")) Is Nothing Then
Range("L9").Sort Key1:=Range("L10"), _
Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
End If
End Sub
This happens because your insert macro changes the range your named range formula refers to, just like it would any normal formula.
The formula has a reference to cell $L$10. When you execute
Range("L10:P10").Insert Shift:=xlDown
any formula, including the named range formula, that referes to a cell on or below row 10 will be updated to refer to a cell one row down (ie $L$11 in this case)
You can fix this by changing your named range formula to this
=OFFSET(Sheet1!$L$1,9,0,COUNTA(Sheet1!$L:$L),1)
Notice it now refers to cell $L$1 so is not affected by the insert.
Note:
You insert macro could do with some work
Try this instead
Sub InsertRooms() ' renamed to avoid using a built in function name
Range("A2:E2").Copy
Worksheets("Sheet1").Range("L10:P10").insert Shift:=xlDown
Application.CutCopyMode = False
End Sub

How to paste value of a sheet using VBA?

I have always used following to make a sheet to contain only values:
Sheets("NameOfTheTab").Activate
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:= xlPasteValues
But this is not safe, if someone/event change the selection, the program runs into random behaviour. How can can I get rid of this pattern?
Well, for one thing, you can avoid selecting the cells, just directly copy them:
Sheets("NameOfTheTab").Activate
Cells.Copy
Cells(1,1).PasteSpecial Paste:= xlPasteValues
Although this might not be the fastest way, depending on your sheet/actual problem.
You should always avoid using select method, beacuse it is not reliable. The sub below is a sample to copy data from a worksheet and paste only values to another one. This sample sub assumes you are running this macro from your target workbook if not change ThisWorkbook to your target workbook.
Sub copy_paste_only_values()
'will copy all cells in your tab that contain data
ThisWorkbook.Worksheets("NameOfTheTab").Cells.Copy
'will paste only values to your target worksheet
ThisWorkbook.Worksheets("NameOfTheTargetTab").Range("A1")._
PasteSpecial Paste:=xlPasteValues
'empty the clipboard
Application.CutCopyMode = False
End Sub

Run time Error - 438

I have the following code in which I am trying to copy data from one sheet to another in same workbook. When I run the code I get Runtime error -438
Sub Copy()
Sheets("Sheet1").Range("A1:D20").Copy
Sheets("Sheet2").Activate
Range("E1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
Try the following code. You should not rely on Activate and Select.
Sub ZCopy()
Sheets("Sheet1").Range("A1:D20").Copy
Sheets("Sheet1").Paste Destination:=Worksheets("Sheet2").Range("E1")
Application.CutCopyMode = False
End Sub
Interesting Reads
MSDN
How to avoid using Select in Excel VBA macros
Do you have a particular need for copy and paste? This can be slow and inefficient. If you're just copying data from one sheet to another, you can set the values of one range equal to the values of another range and avoid the whole thing.
Sheets("Sheet2").Range("E1:H20").Value = Sheets("Sheet1").Range("A1:D20").Value
This will set the range from cells E1:H20 on Sheet2 to the same values as those in the range A1:D20 on Sheet1, which is effectively a copy and paste. I should add that this will work only for the values themselves.
If there is specific formatting (or formulas) that you need copied and pasted, this method won't work.