I've only just come across VBA so I'm a complete novice. Essentially I'm currently automating a form that requires writing out the questions, potential answers, instructions, etc. for developers on a spreadsheet. I've created a basic template table so all the questions are structured the same. I want to copy and paste this table (clearing the contents and taking off the number of the question) and paste it 2 rows down from the bottom of the last table.
The code works fine if I just wanted to copy and paste the table directly below the first but I can't go any further than that. I'm not sure how to write that I want it to find the last filled in row and paste the table 2 rows below.
Sub Macro2()
'
' Macro2 Macro
'
' Keyboard Shortcut: Ctrl+g
'
Range("C2:G6").Select
Selection.ClearContents
Range("A2").Select
ActiveCell.FormulaR1C1 = "C"
Range("A2:G6").Select
Selection.Copy
Range("A8").Select
ActiveSheet.Paste
End Sub
You can completely avoid using select in order to achieve your goal. In the following code, Source is the range of your table, LastRow finds the last row of your table and DestRng is the destination where you want a copy of your table. Hope this helps!
Sub Macro2()
'
' Macro2 Macro
'
' Keyboard Shortcut: Ctrl+g
'
Dim TblRng As Range
Set TblRng = Range("C2:G6")
TblRng.ClearContents
Dim Source As Range
Set Source = Worksheets("Sheet2").Range(("A2"), Range("G2").End(xlDown))
Source.Copy
Dim LastRow As Long
LastRow = Cells(Rows.Count, "G").End(xlUp).Row
Dim DestRng As Range
Set DestRng = Source(LastRow + 1, "A")
DestRng.PasteSpecial xlPasteAll
End Sub
Related
I have a column of data on one sheet that I am transposing to the last row of another sheet. Since I need to cherry pick which cell goes to where I cannot use a transpose function so I wrote the following macro:
Sub Copy_to_empty_row_test()
Dim cs As Worksheet 'Worksheet to copy from
Dim ps As Worksheet 'Worksheet to copy to
Set ps = Worksheets("Test")
Set cs = Worksheets("Imports")
ps.Range("A258:C258").Copy
ps.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulas
'Date check
cs.Range("B1").Copy
ps.Cells(Rows.Count, 1).End(xlUp).Offset(1, 3).PasteSpecial xlPasteValues
'OT
cs.Range("B4").Copy
ps.Cells(Rows.Count, 1).End(xlUp).Offset(1, 4).PasteSpecial xlPasteValues
ThisWorkbook.Worksheets("Test").Range("I245").Copy
ps.Cells(Rows.Count, 1).End(xlUp).Offset(1, 8).PasteSpecial xlPasteFormulas
End Sub
The issue I am running in to is that my data will copy to 2 rows instead of one row. So I will get one row with the formula and then a new row with the data. I have tried changing the code around, with this being the latest iteration, but I still end up with 2 rows of data instead of one.
Can anyone help with what I am missing?
Thanks.
Copy Ranges
The issue is that when you copy the first cells, you are also copying to column A where you are doing the End(xlUp). So when doing it the second time the previous first available row in column A is occupied and the code copies the rest to the row below.
I have assumed that you are copying all cells from the copy worksheet. If that's not the case, as in your code, you can easily replace cws with pws in the first copying lines.
Sub CopyToEmptyRowTest()
' Reference the workbook ('wb').
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Reference the Copy worksheet ('cws').
Dim cws As Worksheet: Set cws = wb.Worksheets("Imports")
' Reference the Paste worksheet ('pws').
Dim pws As Worksheet: Set pws = wb.Worksheets("Test")
' Reference the first available cell ('pCell') in the Paste worksheet.
Dim pCell As Range
Set pCell = pws.Cells(pws.Rows.Count, "A").End(xlUp).Offset(1, 0)
' Copy.
cws.Range("A258:C258").Copy
pCell.PasteSpecial xlPasteFormulas
'Date check
cws.Range("B1").Copy
pCell.Offset(0, 3).PasteSpecial xlPasteValues
' Alternatively, more efficient is copying values by assignment:
'pCell.Offset(0, 3).Value = cws.Range("B1").Value
'OT
cws.Range("B4").Copy
pCell.Offset(0, 4).PasteSpecial xlPasteValues
' Alternatively, more efficient is copying values by assignment:
'pCell.Offset(0, 4).Value = cws.Range("B4").Value
cws.Range("I245").Copy
pCell.Offset(0, 8).PasteSpecial xlPasteFormulas
End Sub
I'm trying to write code to find the next free row in a work book to copy 4 cells of data from one workbook to another.
The code I've used works fine when I run it first time round (and there's nothing in the workbook). It selects A2 and pastes in the 4 cells of data. However when I try to run the same macro again, it selects B2, instead of A3?
I've used this function multiple times before but I've never seen anything like this before. My code is below.
'
' Macro6 Macro
'
Dim fRow As Long
With ActiveSheet
fRow = .Cells(.Rows.Count, 1).End(xlUp).Row
.Cells(fRow).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues
End With
End Sub
The issue is that Cells needs a row and column like .Cells(fRow, "A")
Option Explicit
Public Sub PasteRows()
With ActiveSheet
Dim fRow As Long
fRow = .Cells(.Rows.Count, 1).End(xlUp).Row
.Cells(fRow, "A").Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With
End Sub
also don't use .Select it is a bad practice: You might benefit from reading
How to avoid using Select in Excel VBA.
Alternatively use the following which is even shorter:
Option Explicit
Public Sub PasteRows()
With ActiveSheet
.Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With
End Sub
I have a vba macro that is attempting do some light formatting of data in one workbook then paste the formatted data into the bottom of a table in another workbook. For some reason I am getting a Run-time error '1004': PasterSpecial method of Range class failed when it goes to paste and I can't figure out why.
Sub Add_Data()
'
' Add_Data Macro
'
' Insert column to the left of column B in raw data
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
' Copy columns A-N in raw data
Range("A2").Select
Selection.End(xlDown).Select
Range("A2:N" & ActiveCell.Row).Select
Selection.Copy
' Remove filter from column B of ongoing report
Windows("Ongoing Report.xlsm").Activate
ActiveSheet.ListObjects("OpenJobs_DATA").Range.AutoFilter Field:=2
' Paste data from raw data at bottom of ongoing report
Range("A2").Select
Selection.End(xlDown).Select
Range("A" & ActiveCell.Row + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' Filter column B of ongoing report to remove blanks
ActiveSheet.ListObjects("OpenJobs_DATA").Range.AutoFilter Field:=2, _
Criteria1:="<>"
Copy Range to Range
Carefully adjust the values in the constants (Const) section.
It is assumed that the code will be in the workbook containing the
RawData worksheet.
Tips
The last or first used cells (rows, columns) are usually calculated
from the bottom or from the right. I might be wrong here if you have data below Source Range.
Anything containing Select and Active is best avoided, if possible.
When pasting values, using Copy(Paste) is easily (best) avoided.
The Code
Sub Add_Data()
Const cSource As String = "RawData" ' Source Worksheet Name
Const cCols As String = "A:N" ' Source Columns Range Address
Const cFr As Long = 2 ' Source/Target First Row Number
Const cWbTarget As String = "Ongoing Report.xlsm" ' Target Workbook Name
Const cTarget As String = "Sheet1" ' Target Worksheet Name
Const cTgt As String = "A" ' Target Column Range
Dim rngS As Range ' Source Range
Dim rngT As Range ' Target Range
' In Source Worksheet
With ThisWorkbook.Worksheets(cSource)
' Insert column to the left of column B in raw data.
.Columns("B:B").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
' In Source Columns Range
With .Columns(cCols)
' Calculate and create a reference to Source First Column Last Used
' Cell.
'Set rngS = .Cells(.Row, .Column).End(xlDown)
Set rngS = .Cells(.Rows.Count, .Column).End(xlUp)
' Calculate and create a reference to Source Range.
Set rngS = .Rows(cFr).Resize(rngS.Row - cFr + 1)
End With
End With
' In Target Worksheet
With Workbooks(cWbTarget).Worksheets(cTarget)
' Remove filter from column B of ongoing report
.ListObjects("OpenJobs_DATA").Range.AutoFilter Field:=2
' Calculate and create a reference to Target Column First Empty Cell.
Set rngT = .Cells(.Rows.Count, cTgt).End(xlUp).Offset(1)
' Calculate and create a reference to Target Range i.e. adjust the size
' to be equal to the size of Source Range.
Set rngT = rngT.Resize(rngS.Rows.Count, rngS.Columns.Count)
' Copy values from Source Range to Target Range.
rngT = rngS.Value
' Filter column B of ongoing report to remove blanks
.ListObjects("OpenJobs_DATA").Range.AutoFilter Field:=2, Criteria1:="<>"
End With
End Sub
You lose your clipboard data when you unfilter the table in your destination workbook. They unfiltering first then copying the original range. Also, there almost never a good reason to use select. It can slow down your macros.
Sub Add_Data()
Dim home As Worksheet: Set home = ActiveWorkbook.Sheets("sheet name 1")
Dim dest As Worksheet: Set dest = Windows("Ongoing Report.xlsm").Sheets("sheet name 2")
'Insert column to the left of column B in raw data
home.Columns("B:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'Remove filter from column B of ongoing report
dest.Sheets("sheet name here").ListObjects("OpenJobs_DATA").Range.AutoFilter Field:=2
'Copy columns A-N in raw data
home.Range("A2", Range("A2").SpecialCells(xlEnd).Copy
'Paste data from raw data at bottom of ongoing report
dest.Range("A" & dest.Range("A2").End(xlDown).Row + 1).PasteSpecial xlPasteValues
'Filter column B of ongoing report to remove blanks
Dest.ListObjects("OpenJobs_DATA").Range.AutoFilter Field:=2, Criteria1:="<>"
End Sub
Untested from my mobile, but hope this points you in the right direction.
What I'm trying to do is open one workbook, copy all the data on the first sheet of it and then adding that data to the first empty row of a sheet in another workbook. I seem to run into a problem when pasting the data but I don't fully understand why. I have run the code and just copied the top row of a sheet and then used my method of finding the first empty row and pasting it there which has worked, so I must be something with how I'm copying / selecting my date.
Here is the code :
MyFile6.Activate
MyFile6.Worksheets(1).Activate
Cells.Select
Selection.Copy
Windows("Frávikagreining.xlsm").Activate
Sheets("Laun").Select
Dim Rng As Long
Rng = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(Rng, 1).Select
ActiveSheet.Paste
I have already defined and opened the workbook "MyFile6" (code not shown here). So I copy the data on the first sheet of this workbook MyFile6, then I open the sheet "Laun" at another workbook, find the last used row in column A, go one further down (first empty cell) and select that. But then my paste attempt is stopped by an error.
Any help / better way to do this would be greatly appreciated !
Cells.Select
Selection.Copy
You are getting that error because you are copying ALL Cells but not pasting in A1. And hence the error. You are trying to fit a bigger object into a smaller object. Work with realistic range objects instead of All Cells by finding last row in first sheet as well and then identifying the range to copy and then pasting accordingly.
Also avoid the use of .Select/Activate. You may want to see How to avoid using Select in Excel VBA
Your code can be written as (UNTESTED)
Dim lRow As Long, lCol As Long
Dim rngToCopy As Range
Dim thatWb As Workbook
'~~> Destination Workbook
Set thatWb = Workbooks("Frávikagreining.xlsm")
With MyFile6.Worksheets(1)
'~~> Find last row and column
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'~~> Set your range to copy
Set rngToCopy = .Range(.Cells(1, 1), .Cells(lRow, lCol))
End With
With thatWb.Sheets("Laun")
'~~> find last row in destination sheet for pasting
lRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
'~~> Copy and paste
rngToCopy.Copy .Range("A" & lRow)
End With
Complete amateur here. I've been puzzling over this for hours, and I can't find anything to help me in any other thread. At my wit's end so sorry if this has been asked elsewhere.
I'm trying to create a ridiculously simple macro to do the following:
Go to Sheet2,
Select C6:C10
Copy
Go to Sheet3
Insert copied cells in B2 and shift the other cells down.
I did this just by recording the macro, but each time I do it, I get different errors. The error I currently have is 'Insert Method of Range Class Failed', but sometimes the error pops up at 'Selection.Copy'. This is the code I have:
Sub InsertCellsShitDown()
'
' InsertCellsShitDown Macro
'
'
Sheets("Booking Sheet").Select
Range("C6:C10").Select
Selection.Copy
Sheets("Sheet1").Select
Range("B2").Select
Selection.Insert Shift:=xlDown
End Sub
Any help would be hugely appreciated.
Sub InsertCellsShiftDown()
'
' InsertCellsShitDown Macro
Dim bookingWS As Worksheet, mainWS As Worksheet
Dim copyRng As Range
Set bookingWS = Sheets("Booking Sheet")
Set mainWS = Sheets("Sheet1")
Set copyRng = bookingWS.Range("C6:C10")
mainWS.Range("B2:B" & copyRng.Rows.Count + 1).Insert Shift:=xlDown
copyRng.Copy mainWS.Range("B2")
End Sub
How does this work? I assume you wanted to insert 5 rows, so from B2:B7, then put the data.