Copy and Paste (transposed & values) a set range in a different sheet in the next empty row - vba

I have some data in range P1:R13 on a sheet called Training Analysis.
I want to copy and paste these data on a second sheet called Foglio1. I want it to be just values. I need these data to be pasted in a range A2:M4, in other words I want it to be transposed.
I got the following code and it is working. But now, when I get new data I need to paste them under those I already have.
Sub add()
Dim lastrow As Long
lastrow = Sheets("Foglio1").Range("A65536").End(xlUp).Row ' or + 1
Range("P1:R13").Copy Destination:=Sheets("Foglio1").Range("A" & lastrow)
End Sub
It does the empty space but I don't know how to change it to make it transpose the data and give me only values.
Can you help me change it ? If you have new options its fine too.
Cheers

What you need to do when you have a question like this is to record a macro, understand how it works and then clean up the code.
This is what you will get after doing what you need manually and recording it:
Range("P1:R13").Select
Selection.Copy
Sheets("Foglio1").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
After you clean it up a bit and add determining the last row this is what you should get:
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
In this particular case you didn't know that you need to use the PasteSpecial method but this is okay: you don't need to remember the entire Excel object model by heart. You can use the 'record, clean up and modify' method whenever you are in a situation like this.

You could shorten it further and try:
Sub add()
Range("Foglio1!A2:M4").Value2 = Application.WorksheetFunction.transpose(Range("Training Analysis!P1:R13").Value2)
End Sub
This is, of course, adapted to this specific case, so, for further use, you must ensure you update the sheet names and ranges(if they change). You also have to check by yourself that the areas are equivalent (e.g. 15x2 to 5x6 cells). These checks can be added in the procedure, but the code above should do the trick for the moment.
EDIT: I saw your specification a bit too late. :)
Here is the adapted code, which should find the first available row on sheet "Foglio1", column A, and will paste the transposed values onto a 3x13 area. Give it a go.
Sub add2()
With Sheets("Foglio1")
.Cells(.Range("A" & .Rows.Count).End(xlUp).Row + 1, 1).Resize(3, 13).Value2 = _
Application.WorksheetFunction.Transpose(Sheets("Training Analysis").Range("P1:R13").Value2)
End With
End Sub
EDIT 2: updated add2 so that the source range would refer to sheet "Training Analysis" and prevent error# 1004.

Related

VBA not updating Excel rows referring to other sheets in same workbook when sorting rows alphabetically

I'm having problems, Excel is not updating rows referring to other sheets in same workbook when ordering rows alphabetically.
I have a userform in which there's a button insertCM with this code:
Private Sub insertButton_Click()
ActiveCell.EntireRow.Select
Selection.Insert Shift:=xltoDown
Range("A9:AK9").Copy
Range("A8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Selection.PasteSpecial Paste:=xlPasteFormats
Range("C10").Copy
Range("C8:C9").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy
Range("H8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteAll
nomCM = Empty
CXinitial = Empty
resteCX = Empty
CCselect = Empty
C4initial = Empty
resteC4 = Empty
compteurCT = Empty
Range("A8").Activate
ActiveCell.RowHeight = 18.6
For i = 2 To ThisWorkbook.Sheets.Count
With Sheets(i).Select
emptyRow = Range("A9").End(xlDown).Offset(0, 2).Row
Range("A9:AL" & emptyRow).Sort _
Key1:=Range("A9"), Order1:=xlAscending
Set SearchRange = Range("A8", Range("A200").End(xlUp))
Set FindRow = SearchRange.Find(nomCM, LookIn:=xlValues, LookAt:=xlWhole)
Range("A" & FindRow.Row).Select
ActiveCell.EntireRow.Activate
End With
Next i
Sheet2.Select
End
End Sub
The userform is used for inserting new clients in several sheets at the same time. Textbox inserts Name, Cost Center, etc., in a blank row and insertButton inserts a new row leaving data inserted in row 8 to go to row 9. After that the code puts all rows alphabetical order so the new client now in row 9 goes to the new one, and cells containing formulas change row numbers.
However some of the sheets have cells containing references to other sheets' cells in the same row. So imagine:
I insert client name "LORUM" "Cost Center 4" and it puts him in row 9 so formula is:
=$C9-COUNTIF($E9:$P9;"CT")+'Sheet5'!$D9
...but when it changes his row to the final one, formula row is:
=$C18-COUNTIF($E18:$P18;"CT")+'Sheet5'!$D9
It does not change row when referring to other sheets.
Any ideas?
It's looks like you've made a good effort, but there are still numerous problems with your code (beside the one line), and I can guarantee that a combination of these issues are preventing your intended outcome.
I can't fix it completely because there are so many bugs that I'm not clear on what you're trying to do, but hopefully this will get you started on the right track...
xlToDown is not a valid reference. You probably mean xlDown
you have a number of undeclared variables and objects, like: i, emptyRow, SearchRange, FindRow, nomCM
you have things (objects?) "set to nothing" that aren't declared or used anywhere: CXinitial, resteCX, CCselect, C4initial, resteC4, compteurCT
your Find statement is looking for nomCM which is empty (and never set), so the Find statement will never find anything.
You should put Option Explicit at the top of every module (especially when learning or troubleshooting). This will prevent issues like the ones above by "forcing" you to properly declare & handle all of your variables, objects, properties, etc.
Near the end, you refer to Sheet2.Select as if Sheet2 is a declared object, instead of using Sheets("Sheet2").Select. I'm not sure why you're selecting the sheet at the very end anyhow.
You have an With..End statement that is doing absolutely nothing since you don't reference it with a . dot anywhere: With Sheets(i).Select .. End With, and also Select isn't used like that.
A mystery End near the end for some reason.
Also, you're unnecessarily doubling up commands like:
ActiveCell.EntireRow.Select
Selection.Insert Shift:=xlDown
..instead of:
ActiveCell.EntireRow.Insert Shift:=xlDown
and another example, all this:
Range("A9:AK9").Copy
Range("A8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Selection.PasteSpecial Paste:=xlPasteFormats
Range("C10").Copy
Range("C8:C9").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy
Range("H8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteAll
...instead of:
Range("A9:AK9").Copy
Range("A8:AK8").PasteSpecial xlPasteValuesAndNumberFormats
Range("C10").Copy
Range("C8:C9").PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy Range("H8:AK8")
All of this would be more clear by Googling the documentation for each command you're unfamiliar with, such as:
Range.Copy Method (Excel)
Range.PasteSpecial Method (Excel)
XlPasteType Enumeration (Excel)
All the ActiveCell and ThisWorkbook references are troublesome but again, I'm not sure what to do with them since I don't know your workbook.
Indentation (and general organization) are very important as well. It may not change the way that the code runs, but it will help you (and others) track down existing & potential issues more easily.
Here is your code cleaned up as best as I could:
Option Explicit 'this line goes at the very top of the module
Private Sub insertButton_Click()
Dim i As Long, emptyRow As Long, SearchRange As Range, FindRow As Range, nomCM
nomCM = Empty
ActiveCell.EntireRow.Insert Shift:=xlDown
Range("A9:AK9").Copy
Range("A8:AK8").PasteSpecial xlPasteValuesAndNumberFormats
Range("C10").Copy
Range("C8:C9").PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy Range("H8:AK8")
Range("A8").RowHeight = 18.6
For i = 2 To ThisWorkbook.Sheets.Count
With Sheets(i)
emptyRow = .Range("A9").End(xlDown).Offset(0, 2).Row
.Range("A9:AL" & emptyRow).Sort Key1:=.Range("A9"), Order1:=xlAscending
Set SearchRange = .Range("A8", .Range("A200").End(xlUp))
Set FindRow = SearchRange.Find(nomCM, LookIn:=xlValues, LookAt:=xlWhole)
.Range("A" & FindRow.Row).Select
ActiveCell.EntireRow.Activate
End With
Next i
Sheets("Sheet2").Select
End Sub
as per my test, sorting actually doesn't change other sheet direct references
so you may want to use OFFSET to keep referencing the actual current row index
instead of:
=$C9-COUNTIF($E9:$P9;"CT")+'Sheet5'!$D9
use
=$C9-COUNTIF($E9:$P9;"CT")+ OFFSET('Sheet5'!$D1,ROW()-1,0)
I found a solution:
=INDIRECT(ADDRESS(ROW();4;3;1;"Sheet5"))
Where Row() will always refer to the actual cell's row.
Hope it will help you!

VBA : wrong formula - freezing and not enough memory message

I have a code on VBA that makes my Excel freezing (filling cells) and gives a output message like "not enough memory to run" + error 1004, but I don't understand why because it's really a simple formula.. There's only one part of the full code that causes the issue and here is it:
Sub mismatches()
Dim sht As Worksheet, cell As Range, areaToTrim As Range, LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set sht = ThisWorkbook.Worksheets("Mismatches")
sht.Activate
Range("O1").EntireColumn.Insert
sht.Cells(1, 15) = "Mismatch DRP"
Range("02:0" & LastRow).Value = _
"=IF(ISNA(VLOOKUP(K2,CDL_data!D:D,1,0)),""N/A"",I2)"
Range("02:0" & LastRow).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
I'd like to precise that the other parts of the code are almost exactly the same, only the formula is different, but they run properly! Something has to be "wrong" or "too heavy" in the formula, even if I've already used this kind of formula. I've tried the full code with only 3 rows (on sheet "Mismatches") but there are 9000 rows in the sheet "CDL_data" (used for the Vlookup).
You probably have a typo, using zero instead of the letter O in the column reference. This means that you are referencing a number of whole rows, probably 9000 of them and inserting a Vlookup function into 16384 cells per row, which is roughly 147 Million cells that will need to calculate the Vlookup.
You probably want to change this part of the code from using a zero
Range("02:0" & LastRow).Value = _
"=IF(ISNA(VLOOKUP(K2,CDL_data!D:D,1,0)),""N/A"",I2)"
Range("02:0" & LastRow).Select
to this, using the letter O as the column reference:
Range("O2:O" & LastRow).Value = _
"=IF(ISNA(VLOOKUP(K2,CDL_data!D:D,1,0)),""N/A"",I2)"
Range("O2:O" & LastRow).Select
You may want to change your VBE font to something that uses a distinctly different character for Zero as compared to uppercase O, to avoid such mistakes. Consolas uses a diagonal strike on a zero, which makes it very easy to distinguish it from an O.
In general, if you want your code to run faster, avoid selecting things and then acting on selections. In most cases it is possible to act on the range directly.

Copy sheet to another workbook in VBA does not copy

I am trying to copy a specific sheet from one workbook to another but it seems that it does not copy the content of the sheet and returns an empty one.
Second problem is that when I copy the sheet I use Sheet.Count to create another sheet in my workbook where I paste the new sheet but it is not working properly as it does not create a new one as and instead takes my last one and renames it and then deletes it.
What could it be wrong and how do I add error handling code?
Sheets(filesheet).COPY After:=ThisWorkbook.Sheets(Sheets.Count)
'Application.AskToUpdateLinks = False
wb.Close savechanges:=False
'naming of the copied sheet
ActiveWorkbook.Sheets(Sheets.Count).Name = "Imported data"
'copy the material as values to sourcing template sheet
Sheets("Imported data").Cells.COPY
Sheets("Sourcing template").Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'delete the imported copied sheet (named ranges etc, to avoid file size growing too much)
Sheets("Imported data").Delete
There are tons of problems here but ill try to explain some....
Dont copy and paste. You thisCell.Value = ThatCell.Value instead.
Referencing Active(whatever) is going to eventually lead you to bad results. It may seem like a pain point to type more, but explicitly spelling it out what workbook/sheet/whatever you are intending to reference will solve alot of frustration in the future.
Here is most likely how i'd approach this like this. This is easily modified to do all sheets in a work book.
Dim sheetCopy as variant
dim sheet as Worksheet
dim rowC as long
dim colC as long
set sheet = ThisWorkBook.Sheets("Imported Data")
rowC = sheet.UsedRange.Rows.Count
colC = sheet.UsedRange.Columns.Count
sheetCopy = sheet.UsedRange
ThisWorkBook.Sheets("Sourcing template").Range(ThisWorkBook.Sheets("Sourcing template").Cells(1,1), ThisWorkBook.Sheets("Sourcing template").Cells(rowC,colC).Value2 = sheetCopy
sheet.Delete
To be frank, I don't fully understand your question.
But base on my understanding, this code works for me. The filesheet in Sheets(filesheet) doesn't make sense for me, so I've changed it to "Sheet1". You can change it ot your exact sheet name.
Sub test()
Sheets("Sheet1").Copy After:=ThisWorkbook.Sheets(Sheets.Count)
ActiveWorkbook.Sheets(Sheets.Count).Name = "Imported Data"
Sheets("Imported data").Cells.Copy
Sheets("Sourcing template").Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Imported data").Delete
End Sub
The code copy all the content of Sheet1 to new sheet and change the new sheet name as "Imported data".
Then, copy all cells in "Imported data" and paste only the values to "Sourcing template". Thus, only values will be shown in "Sourcing template" (any chart or table will be ignored).
If you wish to paste all the content including formatting, you should use Activesheets.Paste instead.

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

VBA - Copy and Paste Dynamic Range with Dynamic Start Point

I am very new to the VBA community and usage so my illiteracy is a bit embarrassing. I work in a lab that routinely deals with very large data output files. In order to statistically analyze these data files we often have to rearrange the output data into a more statistically friendly format. Therein lies my problem.
I have created and VBA that does this for a very specific dataset, copying and paste transposing 5 data points at a time. I would like help in creating something that allows me to have a more generic approach to this where I might be able to enter the number of study time points (typically between 3 and 10) and the number of study participants (between 10 and 100) and still get the copy/paste transpose done on the correct sheet.
What I have in my specific VBA is below. I basically have this done manually all the way to a range of B208:212 and all the way through Sheet 13.
Sheets("Raw Data").Select
Range("B3:B7").Select
Selection.Copy
Sheets("Sheet1").Select
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
What this does is copies five data points for one study participant, goes to my desired sheet, and paste transposes in the row corresponding with my study participant. I need to do this for up 100 study participants, each beginning on its own row starting with D2.
Sorry this is confusing. I am working on posting more clarification below.
Sheets("Raw Data").Select
Range("B3:B7").Select
Selection.Copy
Sheets("Sheet1").Select
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
reduces to
Sheets("Sheet1").Range("D2").Resize(5, 1).Value = _
Application.Transpose(Sheets("Raw Data").Range("B3").Resize(1, 5).Value)
Taking that as a starting point, you can declare some variables (or better, use Constants) for the "5", etc, but you'd need to add some more details to your question, including what dtermines where the next "paste" point is. you mention multiple sheets but it's not clear how those are involved in the operation.
Eg:
Sub Tester()
Const DATA_PTS As Long = 5
Dim rngCopy As Range, rngPaste As Range
'start point for source data
Set rngCopy = Sheets("Raw Data").Range("B3").Resize(DATA_PTS, 1).Value
Do While Application.CountA(rngCopy) > 0
'Set rngPaste = ? 'what determines where data is copied to?
rngPaste.Resize(1, DATA_PTS).Value = _
Application.Transpose(rngCopy.Value)
'next source range
Set rngCopy = rngCopy.Offset(DATA_PTS, 0)
Loop
End Sub