VBA Code works differently in different workbooks - vba

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

Related

Macro for copying certain cells between excel worksheets

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.

How do I freeze the active row in excel with VBA?

Like the title says, I need to write a VBA code that copies the entire row i selected and pastes only the values so the results cannot be changed afterwards.
I have already managed to do this for the ActiveCell in the last file I worked on, but I only had to change one cell then. This is the code I used:
Sub Freeze()
ActiveCell.Copy
ActiveCell.PasteSpecial Paste:=xlPasteValues
End Sub
However, for this new file I have to copy the entire row and i don't want to select each individual cell. When I use this in the new file, it only works on the first cell. How can I make it work for the entire row?
Thanks.
Use the simple code below (try to avoid Selecting cells, and active cells if possible):
Sub Test()
Call Freeze(3, 7)
Call Freeze(4, 8)
End Sub
Sub Freeze(rowsource As Long, rowdest As Long)
Rows(rowsource).Copy
Rows(rowdest).PasteSpecial Paste:=xlPasteValues
End Sub
Paste:=xlPasteValues
You do not need to copy paste values unless you are trying to copy formats as well.
Try this. Replace the sheet names with the relevant sheet names. Also Replace X,Y with the relevant row numbers. If you are using multiple rows then change Rows(X) to Range("X:X") and similarly Range("Y:Y")
Thisworkbook.Sheets("Sheet1").Rows(X).Value = _
Thisworkbook.Sheets("Sheet2").Rows(Y).Value

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

Copy formula from a specific sheet and cell and drag it down until specific column last row

So far I have this code below; counting last cell is working fine but is copy/pasting the wrong data to wrong sheet. Should copy data and use the formula from Sheet "Parsing" cell B2, and its using the main sheet where is the VBA. Looks lile what is missing is to execute the copy/select to "parsing" sheet, but didnt manage to do it.
Sub drag_formula_original()
Dim myLastRow As Long
With Worksheets("Parsing")
myLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("B2").Copy Destination:=.Range("B2:B" & myLastRow)
Application.CutCopyMode = False
End With
End Sub
Its solved. Thanks a lot.
Range("B2").Copy
The above will grab by default from the Activesheet
you have to tell it what sheet you would like it to pick that range/value from.
sheets("Parsing").Range("B2").Copy
Edit: Just noticed your With
To actually use a with you need to use a "." e.g. your copy line would look like below
.Range("B2").Copy
One other thing to note this:
Range("B2:B" & myLastRow).Select
ActiveSheet.Paste
Is rather inefficient, below would be better. Selecting in general is best to keep away from it is rather slow
Range("B2:B" & myLastRow).Paste
Or with your with
.Range("B2:B" & myLastRow).Paste
I just copied and pasted your code and ran it. I changed nothing in your code except for adding "Option Explicit" before your sub. (Just a personal habit)
Option Explicit
Sub drag_formula_original()
Dim myLastRow As Long
With Worksheets("Parsing")
myLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Range("B2").Copy
Range("B2:B" & myLastRow).Select
ActiveSheet.Paste
Application.CutCopyMode = False
End With
End Sub
I did, however, use a very simple formula in cell B2. What I did was have column A go from 1 to 10 and column C go from 11 to 20. Cell B2 was =A2+C2.
After running the code I checked each cell in column B and they each had the correct formula in them, and not a hard-coded value.
A trick I do when I want to do something like this but can't figure out how is I record a macro of me dragging the cell formula down a little ways and then stop the recording and look at the code it made. From that you should be able to adjust it to do what you want.
When I did that I got this code:
Sub Macro1()
'
' Macro1 Macro
'
'
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B15"), Type:=xlFillDefault
Range("B2:B15").Select
End Sub