Taking columns of data copying and pasting them under eachother VBA - vba

I know this is a real simple solution, but what I want to do is take column D14:E, and paste the numerical values into another part of the worksheet, the correct code is below:
Range("D14", Cells(Rows.Count, "E")).Copy
Range("AH14", Cells(Rows.Count, "AI").End(xlUp)).PasteSpecial Paste:=xlPasteValues
My issue here is when I am trying to take a second set of columns and paste it underneath the one I just pasted. The code I am trying is below:
Range("N14", Cells(Rows.Count, "O")).Copy
Range("AH14" & Cells(Rows.Count, "AI").End(xlUp)).PasteSpecial Paste:=xlPasteValues
Note that the columns are varying sizes (meaning column D could be a different size because of previous variables that were inputted (I had a question that was answered previously if you want to know what I mean)).

Range("N14", Cells(Rows.Count, "O").End(xlUp)).Copy ' Copy columns
Range("AH14").End(xlDown).Offset(1, 0).Select ' Find the first free column, select it
Selection.PasteSpecial Paste:=xlPasteValues 'paste copied cells

Related

Copy and paste active column without changing cells formats

This code helps me to copy and paste active column in values but the numbers are pasted with two decimals. I'm using this code because my sheet has merged cells inside and also some cells within the column have dates.
ActiveCell.Offset(0, 0).EntireColumn.Value = ActiveCell.EntireColumn.Value
I need to paste the column in values exactly in the format that the column has the format. Leave the numbers without the decimals.
Note: If you do it manually by selecting the column and then selecting paste in values from the Home bar, it pastes it exactly as it was with the formulas.
Try it this way:
Dim r As Long
c = Selection.Column
Range(Cells(4, c + 1), Cells(5, c + 1)).Merge
Columns(c).EntireColumn.Copy
Columns(c + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
You may need to tweak some stuff, like merging certain cells, where you want the cell pasted in relation to the copied cell. Let me know how this works

Copying several filtered columns' worth of non blank cells to second sheet

I have a table that I need to autofilter itself according to criteria in column "AS", then copy multiple discrete columns' worth of resulting non-blank cells to specific cells in the next sheet.
What is the most efficient way of doing this? I'm aware that I may have to copy/paste specialvalues instead of direct reference
I'm not entirely sure what you're asking. But, imagine Column A is filled with names of fruits and Column B is filled with numbers. The following code filters Column A with the criteria "Apples" and copies the corresponding numbers to a new worksheet. This might start you off on the right track.
Sub selectApples()
' Find last row in column A
Dim LastRow As Integer
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
' Select data in column A and filter
Range("A1:A" & LastRow).Select
Selection.AutoFilter Field:=1, Criteria1:="Apples"
'Find new last row
Dim newLastRow As Integer
newLastRow = Cells(Rows.Count, 1).End(xlUp).Row
'Copy and paste special into new worksheet
Range("B2:B" & newLastRow).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
Selection.PasteSpecial Paste:=xlPasteValues
End Sub

ClearContents for constants but not formulas

I've got a range (N1:N12) on a sheet1 and I've got a code that copy and paste me the values of that range on a secondary sheet2. Everything is working, anyway i didn't consider that i want another button that clear only values in range N1:N12 once i have copied them in sheet2. I don't know how to keep formulas on that range when i want to delete values. Do you have an idea ? I've already tried a normal macro that deletes everything but it is not what i want.
Sub Cancella()
Sheets("Foglio1").select
Range("N1:N12").clearcontents
End Sub
The code i use for copying
Dim lastRow As Long
Sheets("Training Analysis").Range("P1:R13").Copy
lastRow = Sheets("Foglio1").Range("a65536").End(xlUp).Row
Sheets("Foglio1").Range("A" & lastRow + 1).PasteSpecial Paste:=xlPasteValues, Transpose:=True
Replace:
Range("N1:N12").clearcontents
with:
For i = 1 To 12
If Not Cells(i, "N").HasFormula Then Cells(i, "N").ClearContents
Next i
There is a subset of the Range.SpecialCells method that targets xlCellTypeConstants. This can be further broken down to xlNumbers, xlTextValues, xlErrors , xlLogical or a combination of same.
With WorkSheets("Foglio1")
.Range("N1:N12").SpecialCells(xlCellTypeConstants, xlNumbers).ClearContents
End With
Conversely, cells containing formulas can be similarly targeted with the xlCellTypeFormulas subset.

Macro to copy data from one sheet to another, only if not already present

I am struggling with this macro. I have two sheets; One with a large set of data that is updated by a macro with respect to multiple dates.
I want to copy the data from that sheet ("rawdata1") to another sheet ("sheet1"), but only if the data isn't already present (don't want multiple entries of the same data on "sheet1"). I have no problem copying the data to the other sheet but how do you avoid duplicate entries when the macro is run multiple times?
The code I have so far:
Sub CopyData()
'Copy data if not present in other sheet
'???
Sheets("rawdata1").Select
Range("A4:AC10000").Select
Range("A4:AC10000").Copy
Sheets("Sheet1").Select
' Find the last row of data
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Paste
Sheets("Sheet1").Select
Thanks for the help!
Your code can be simplified to:
Sheets("rawdata1").Range("A4:AC10000").Copy _
Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1,0)
Sheets("Sheet1").Select
As for preventing multiple copies of the same line, if you're in Excel 2007+ then you can use RemoveDuplicates after running the copy: this will reduce the range down to unique rows only. Note: you need to adjust the Columns parameter to include all relevant column numbers.
ActiveSheet.UsedRange("$A$1:$E$8").RemoveDuplicates _
Columns:=Array(1, 2, 3, 4, 5), Header:=xlYes 'or xlNo, depending on your data

Looking to select an undetermined number of rows in excel as part of larger VBA macro

I'm working with an excel book containing a large number of sheets; the first sheet is linked to an external program and pulls in data via an external function, and the number of lines imported varies significantly.
This block data is the disseminated over a number of subsequent sheets. The first step has been to populate column A (row name) with the number of rows in sheet 1. From here the data is split over a number of columns (currently B->L). The top row uses an IF() function to populate the first row, and I'm looking to write a clean macro to copy this formula to row x (which varies with each data import refresh) and then paste values for a manageable file size.
Here's what I've got so far; it works, but it's fairly (read: VERY!) clumsy:
Sub Refresh_Data()
Sheets("Sheet2").Select
ActiveWindow.ScrollWorkbookTabs Sheets:=13
Sheets(Array("Sheet2" ... "Sheet25")).Select
Sheets("Sheet2").Activate
Sheets("Sheet25").Select Replace:=False
Range("B1:L1").Select
Selection.Copy
Range("__B2:B1000__").Select
ActiveSheet.Paste
Application.Calculate
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets(Array("Sheet2" ... "Sheet25")).Select
Sheets("Sheet2").Activate
Sheets("Sheet25").Select Replace:=False
Sheets("Sheet2").Select
Range("B3").Select
Sheets(Array("Sheet2" ... "Sheet25")).Select
Sheets("Sheet2").Activate
Sheets("Sheet25").Select Replace:=False
Range("B3:L4").Select
Range("__B2:L1000__").Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Check_sheet").Select
MsgBox "Update complete"
End Sub`
The main thing I'm looking to achieve is to replace the code B2:L1000 with something that can assess the number of rows in column A and select a range in rows B to L accordingly.
Since column L is the last populated column, I don't see why this can't also be done horizontally rather than defining "B:L" incase future columns need to be added.
Although the earlier answer has merits:
1) I would not use COUNTA because if there are empty cells in the row or column, the cells at the bottom or the right will be ignored.
2) I would never rely on the user picking the correct sheet to be used before running a macro; particularly one with so many sheets.
My reaction to the question is that you have set Macro Record, wandered around your workbook and then stopped the record. You select one thing, then another. You scroll through the sheets. To me most of the statements are not clumsy they are pointless.
The following does include an answer to your question about finding the last row of column A but it is more a tutorial about finding the dimensions of a range, getting data out of the range and then putting it somewhere else. This seems to be most of what you are trying to do with the most minimal understanding of VBA. I am sorry if this criticism is unfair but that is the impression your question gives to me.
Sub Test()
Dim RowS01Max As Integer
Dim Sheet1Data() As Variant
' With Sheets("Sheet1") allows you to access data within worksheet Sheet1
' without selecting it.
' Range("A1:C11") refers to a range within the active sheet
' .Range("A1:C11") refers to a range within the sheet identified in the
' With statement.
' ^ Note the dot
With Sheets("Sheet1")
' Rows.Count is the number of rows for the version of Excel you are using.
' .Cells(Rows.Count, "A") address the bottom row of column A of worksheet
' Sheet1.
' .Cells(Rows.Count, 1) refer to column A by number.
' End(xlUp) is the VBA equivalent of Ctrl+Up.
' If you positioned the cursor at the bottom of column A and pressed
' Ctrl+Up, the cursor would jump to the last row in column A with a value.
' The following statement gets that row number without actually moving
' the cursor.
RowS01Max = .Cells(Rows.Count, "A").End(xlUp)
' The following statement loads the contents of range A1:C11 of
' Sheets("Sheet1") into array Sheet1Data.
Sheet1Data = .Range("A1:C11").Value
' This is the same statement but the range is specified in a different way.
' .Cells(Row,Column) identifies a single cell within the sheet specified in
' the With statement. .Cells(1,1) identifies row 1, column 1 which is A1.
'. Cells(11, "C") identifies row 11, column C which is C11.
Sheet1Data = .Range(.Cells(1, 1), .Cells(11, "C")).Value
' This statement uses RowS01Max to specify the last row
Sheet1Data = .Range(.Cells(1, 1), .Cells(RowS01Max, 1)).Value
' In all three examples above, the contents of the specified range will
' be loaded to array Sheet1Data. Whichever range you pick, Sheet1Data
' will always be a two dimensional array with the first dimension being
' the row and the second dimension being the column.
' In the first two examples Sheet1Data(5,3) contains the contents
' of cell C5. In the third example, I have only loaded column A but the
' array will still has two dimensions but the only permitted value for the
' second dimension is 1.
' The following statement writes the contents of Sheet1Data to column "E"
.Range(.Cells(1, 5), .Cells(RowS01Max, 5)).Value = Sheet1Data
End With
With Sheets("Sheet2")
' The following statement writes the contents of Sheet1Data to column "E"
' of worksheet Sheet2.
.Range(.Cells(1, 5), .Cells(RowS01Max, 5)).Value = Sheet1Data
End With
End Sub
Don't despair! Most of us started with the macro recorder and still use it to discover the syntax for an unfamiliar command. Look through other questions. Some ask about exotic functionality but many are about moving data around in, to the experienced programmer, simple ways. Set up some workbooks with the questioner's problem. Copy and paste the solution into a module. Step through it using F8 (see the debugger), switch between Excel and Editor, watch what is happening to the worksheet and move the cursor over a variable to see its current value. Spend half a day playing. You will be amazed at how quickly it starts to make sense. Good luck and good programming.
The following should do the trick:
Sub Refresh_Data()
Dim lastRow As Integer
Dim lastCol As Integer
Dim entireRange As Range
Dim targetRange As Range
lastRow = Excel.Evaluate("COUNTA(A:A)") ''// count the rows in column A
lastCol = Excel.Evaluate("COUNTA(1:1)") ''// count the columns in row 1
Set entireRange = Range(Cells(1, 2), Cells(lastRow, lastCol))
Set targetRange = Range(Cells(2, 2), Cells(lastRow, lastCol))
entireRange.FillDown
Application.Calculate
targetRange.Copy
targetRange.PasteSpecial Paste:=xlPasteValues
End Sub
Notes:
Excel.Evaluate(...) allows you to use the result of worksheet functions in your VBA macros.
COUNTA(range) is a worksheet function that counts the number of non-blank cells in a given range. In this case, it can be used to determine the total number of rows in your data set, as well as the number of columns in row 1 that have a formula in them.