VBA Copy and pastevalues in another sheet using offset - excel

I want to create an excel with a macro which does this:
It takes a values from one sheet and paste them in another sheet in the first empty Row. I currently have this and this does paste but then the formula, not the values. When I change Paste to Pastespecial it does not work anymore. Can anybody help me with this?
Sub CopyPasteSpecial()
Set wsA = Sheet3
Set wsW = Sheet5
wsA.Range("A3").Copy
Sheet5.Activate
Dim i As Integer
Application.ScreenUpdating = False
NumRows = Range("C5", Range("C5").End(xlDown)).Rows.Count
Range("C5").Select
For i = 1 To NumRows
ActiveCell.Offset(1, 0).Select
Next
Application.ScreenUpdating = True
ActiveSheet.Paste

The (accepted) answer of Sachin Kohli contains so many problems that it is too much to write in a comment. All of them causes errors that can be found thousend times on Stackoverflow.
(a) DonĀ“t use Select and Activate - https://stackoverflow.com/a/10718179/7599798 - You have already a worksheet variable to sheet5 (wsW), so use it.
(b) Copying data (values) between ranges (=cells) can be done without Copy&Paste. This is much faster.
(c) When dealing with row and column numbers, use datatype Long, else you risk an overflow error in large sheets. Basically, use always Long instead of Integer - the data type Integer exists only for historic reasons.
(d) Always put Optiona Explicit at the top of your code and declare all variables. This will save you a lot of headaches because typos in variable names will be caught by the compiler.
Sub CopyPasteSpecial()
Dim wsA As Worksheet, wsW As Worksheet
Set wsW = ThisWorkbook.Sheets("Sheet2")
Set wsA = Sheet1
Set wsW = Sheet2
Dim lastRow As Long
lastRow = wsW.Cells(wsW.Rows.Count, "C").End(xlUp).Row
wsW.Cells(lastRow + 1, "C").Value = wsA.Range("A3").Value
End Sub

Try this below code for pasting as values & no need to iterate to get to the last empty row as well...
Sub CopyPasteSpecial()
Set wsA = Sheet3
Set wsW = Sheet5
wsA.Range("A3").Copy
Sheet5.Activate
Dim i As Integer
Application.ScreenUpdating = False
NumRows = Range("C5", Range("C5").End(xlDown)).Rows.Count
Range("C" & NumRows + 5).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Hope this Helps...

Related

Vlookup from Another Workbook with fill to Last Row

I'm looking to import data from another file (combinedWorkbook) to my master file (the file which is running the code) using a vlookup. I then need it to drag the vlookup down to the bottom row of data (using column M in the masterfile as a reference to when the data ends) with cell I15 being the starting point for the vlookup in the masterfile.
The problem I'm having is that when running the macro the vlookup is happening in cell M10 in my masterfile, not dragging down the vlookup to the end of the data and not referencing the combinedWorkbook.
Any help would be appreciated.
This is what I got so far
Dim combinedBook As Workbook
Dim filter As String
Dim caption As String
Dim combinedFilename As String
Dim combinedWorkbook As Workbook
Dim targetWorkbook As Workbook
MsgBox ("Select Unpaid Capital Extract")
Set targetWorkbook = ThisWorkbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file"
combinedFilename = Application.GetOpenFilename(filter, , caption)
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
ThisWorkbook.Activate
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-8],combinedWorbookSheet1!R1C1:R700000C2,2,0)"
Range("M16").Select
Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
Range("I15:I60297").Select
Range("I60297").Activate
Selection.FillDown
Range("I15").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.End(xlUp).Select
Range("I15").Select
combinedWorkbook.Close False
There are simply too many unknowns in your code to give a specific answer.
Some observations:
1) Always use Option Explicit at the top of your code, it will pick up mistakes and inconsistencies for you.
2) Watch out for unused variables declared in your code
3) Always specify which workbook and worksheet you are working with; don't just put Range ... or Cells.... this leads to all sorts of bugs.
4) Your VLOOKUP syntax for working with another workbook needs to be of the order
'[" & combinedWorkbook.Name & "]Sheet1'
5) xlsx are not text files btw re: your filter
6) For the rest i.e. where you want formulas to go, how you are determining last row etc I am just having to guess. Be specific when coding and try bullet pointing pseudo code first so you are clear what is going on at each stage.
Option Explicit
Sub test()
Dim filter As String
Dim caption As String
Dim combinedFilename As String
Dim combinedWorkbook As Workbook
Dim targetWorkbook As Workbook
MsgBox "Select Unpaid Capital Extract"
Set targetWorkbook = ThisWorkbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file"
combinedFilename = Application.GetOpenFilename(filter, , caption)
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
'Assuming M is used to find last row in targetWorkbook
Dim lastRow As Long
With targetWorkbook.Worksheets("Sheet1") 'this wasn't specified (specify appropriate sheet name)
lastRow = .Cells(.Rows.Count, "M").End(xlUp).Row
'Assuming I is where formula is being put
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]Sheet1'!R1C1:R700000C2,2,0)"
combinedWorkbook.Close False
End With
End Sub
As I understood you need to apply a vlookup formula in your master file gathering data from another workbook.
The proper strucutre is as followed:
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[8],[Book1]Sheet1!R1C5:R23C6,2,FALSE)"
The first bold text is the place of the value you are looking for, relative to the active cell.
The second bold text is the position of your reference table in your other workbook ( here it is book 1).
You can apply this formula to your masterfile by using a loop.
Dim lastRow as Integer
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "M").End(xlUp).Row
endCount = 15 + lastRow
For i = 15 to endCount
ActiveSheet.Cells(i,13).FormulaR1C1 = "=VLOOKUP(RC[-8],[combinedWorkbook]Sheet1!R1C1:R700000C2,2,FALSE)"
next i
This will apply the vlookup formula in the column I starting row 15 searching for the value in the same row but 8 column before (column "A") and will apply for as many row as there are value in the column M.

In Excel, how do you use a list value in a loop to connect the value to a worksheet name?

I am attempting to create a loop but running into a slight snag that I cannot seem to figure out how to fix; hoping that someone can help me.
I have a list of names in Sheet1 Column A that I would like to use their values as the Sheet names when the loop is running.
Example:
Dim Name As String
Names = Sheets("Sheet1").Range("A1").value
But instead of it sticking with Range("A1").Value, I am needing it to swing down the list until it hits a blank row. I found a few different syntax/coding and tried to make it work but got stuck here.
With a list of names in Column A, the code will run directly to the bottom of the list, pull the value of the name and go directly to the that sheet.
Example:
List in Column A:
Mark
John
Jason
The code will grab Jason, go to the Jason worksheet, and enter the formula. However, it skips Mark and John. Not sure how to fix from here.
Any help would be greatly appreciated.
Sub RunTest()
Dim i, lastcell As Long
Dim Name As String
lastcell = Range("A" & Cells.Rows.Count).End(xlUp).Row
Name = Range("A" & Cells.Rows.Count).End(xlUp).Value
Range("A1").Select
For i = 1 To lastcell
Sheets(Name).Select
Range("A1").Select
ActiveCell.Offset(0, 2).Select
ActiveCell.FormulaR1C1 = "=2"
Sheets("sheet1").Select
ActiveCell.Select
ActiveCell.Offset(1, 0).Select
Next I
End Sub
There's no need for all of that select/activate.
Sub RunTest()
Dim c As Range, wb As Workbook, sht As Worksheet
Set wb = ActiveWorkbook
Set sht = ActiveSheet
For Each c In sht.Range(sht.Range("A1"), _
sht.Cells(Rows.Count, 1).End(xlUp)).Cells
If c.Value <> "" Then
wb.Sheets(c.Value).Range("C1").Formula = "=2"
End If
Next c
End Sub
You need to delete the row: Range("A1").Select
the row with the Name must be moved directly to the loop.
For i = 1 to lastcell
name = cells(i,1)
next i
Name = Range("A" & Cells.Rows.Count).End(xlUp).Value ' - this expression chooses the last name, You can delete it

Excel VBA - Copy range from one sheet to another, next empty row

I'm trying to take a range from one sheet and copy it to the next empty row in another sheet (basically, paste into the range A12:D12 for next empty row in the other sheet). The range will never change. I've seen a lot of questions like this, with people saying the answers work great, but I can't get it to work.
Very new to VBA. Here is the code I'm using:
Private Sub CommandButton1_Click()
Dim NextRow As Range
Set NextRow = Range("A" & Sheets("Sheet3").UsedRange.Rows.Count + 1)
Sheet1.Range("A12:D12").Copy
Sheet3.Activate
NextRow.PasteSpecial Paste:=xlValues, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
End Sub
This runs but it doesn't actually paste any values into Sheet3. Is there something I'm missing? Is there a better way to do this?
Thanks!
You just had an issue in the second line defining NextRow.
Is there a better way to do this? It depends on your needs; personally I do not like to activate/select other cells during a VBA macro so e.g. I would get rid of the Sheet3.Activate. I would also copy the stuff 'manually' without using the clipboard to avoid changing the user's clipboard contents.
Private Sub CommandButton1_Click()
Dim NextRow As Range
Set NextRow = Sheet3.Range("A" & Sheet3.Rows.Count).End(xlUp).Offset(1, 0)
Sheet1.Range("A12:D12").Copy
Sheet3.Activate
NextRow.PasteSpecial Paste:=xlValues, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
End Sub

Loop in Excel 2013

I am having problems with getting a loop to run.
I have a Source1 spreadsheet with a list of values in Column A on the CC's tab. Each number is to be copied individually into Cell B1 on the Template tab of the Source2 spreadsheet.
Cell B1 triggers a consolidation of information (mainly indexed info) and displays it in a template - an aggregate picture of lots of background data. I then Copy A1:K71, and paste this into the Output tab of the Source1 spreadsheet.
I want to work down the list in Column A of the CC's tab, and append each output from the Source2 spreadsheet into the Output tab automatically.
I have the copy/paste working, but I am having problems with the loop.
Selection.Copy
Windows("Source2.xlsx").Activate
Range("B1").Select
ActiveSheet.Paste
Range("A1:K71").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Source1.xlsm").Activate
Sheets("Ouput").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
#Andrew, after reading and re-reading your question, I don't think a loop of any kind is necessary. The macro-recorder results you gave above provide information about how you can solve this. I tested this by creating a Source1 Workbook with values placed in column A on a sheet labeled CC's. I also added a sheet labeled Output. Then, I opened a second Workbook with a sheet labeled Template. Here is the sub-procedure I used to produce the result I think you are describing above:
Sub AndrewProject()
' COMMENT: Declare variables used throughout this procedure
Dim InitialVals As Range
Dim OutputVals As Range
Dim FinalResults As Range
Dim FinalOutput As Range
Dim cell As Variant
' COMMENT: Set the range objects so they are easier to manipulate
Set InitialVals = Workbooks("Source1").Worksheets("CC's").Range("A2:A72")
Set OutputVals = Workbooks("Source2").Worksheets("Template").Range("B2:B72")
Set FinalResults = Workbooks("Source2").Worksheets("Template").Range("A2:K72")
Set FinalOutput = Workbooks("Source1").Worksheets("Output").Range("A2:K72")
' COMMENT: This line copies the values in Source1 Workbook and pastes them into Source2 Workbook
InitialVals.Copy
OutputVals.PasteSpecial xlPasteValues
' COMMENT: Additional code goes here to create the desired output. To simplify things, I put a
' function in Source2, column K that concatenates the string "Output" with InitialVals copied
' from Source1. To emulate your Source2 Template, I placed random values between 1 and 1000 in
' Cells A2:A72 and C2:J72.
' COMMENT: Copy the FinalResults from Source2 "Template" tab into the Source1 "Output" tab
FinalResults.Copy
FinalOutput.PasteSpecial xlPasteAll
End Sub
OK #Andrew...this has got to be my last attempt. I believe this answers your question.
Sub AutomateIt()
' Declare your variables
Dim cell As Range
Dim Src1CC As Range
Dim Src2Template As Range
Dim Src2Calcs As Range
Dim Src1Output As Range
Dim NextRow As Long
Dim count As Integer
' Set the ranges so they can be manipulated
Set Src1CC = Workbooks("Source1").Worksheets("CC").Range("A1")
Set Src2Template = Workbooks("Source2").Worksheets("Template").Range("B1")
Set Src2Calcs = Workbooks("Source2").Worksheets("Template").Range("A1:K72")
Set Src1Output = Workbooks("Source1").Worksheets("Output").Range("A1:K72")
Src2Template.ClearContents
count = 0
' Loop through all the cells and calculate stuff
For Each cell In Src1CC.Range(Src1CC, Src1CC.End(xlDown))
'Determine the next empty row (plus a space for readability)
NextRow = Cells(Rows.count, 1).End(xlUp).Row + 2
'Send a copy of the Src1CC cell value to the Src2Template
cell.Copy Src2Template
'Re-calculate A1:K72 based on cell value
Src2Calcs.Calculate
'Copy Src2Calcs results and paste to Source1 Output
Src2Calcs.Copy
Src1Output.PasteSpecial xlPasteValues
count = count + 1
MsgBox "You have pasted " & count & " results."
'Change Src1Output Range so that the next paste is the next blank row
'plus one additional row for readability.
Set Src1Output = Workbooks("Source1").Worksheets("Output").Range(Cells(NextRow, 1), Cells(NextRow, 11))
Next cell
End Sub

Macro to delete contents of cells using their references

I have a list of references of cells to be deleted. The list of references is in sheet "test_url". The list of references point to cells to be deleted that are in another sheet "main_lists".
What I am after is a macro that takes all the references listed in "test_url" sheet, and select their cells in "main_lists" sheet and delete them.
The following macro is what I recorded for two references only in an attempt to demonstrate my problem that necessitated me to copy the reference from "test_url" sheet, then paste it in the NameBox of "main_urls" sheet to select the contents of the designated cell then delete its contents. This process was done manually one cell at a time for a list of 10-20 addresses/references. However, recently this list is over 2000 entries and it is growing:
Sub DeletePermittedCells()
'DeletePermittedCells Macro
Sheets("test_urls").Select
Range("B2").Select
Sheets("test_urls").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R200045C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
Range("B3").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R247138C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
End Sub
Can someone help with this issue please?
Try this one:
Sub DeletePermittedCells()
Dim rng As Range
Dim arr, c
With Sheets("test_urls")
'storing data in array makes your code much faster
arr = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
End With
With Sheets("main_lists")
Set rng = .Range(arr(1, 1))
For Each c In arr
Set rng = Union(rng, .Range(c))
Next
End With
rng.ClearContents
End Sub
storing addresses in array (rather than reading each cell from worksheet directly) makes your code much faster.
Note, code assumed that your addresses stored in range B2:B & lastrow where lastrow - is row of last cell with data in column B
This assumes that the list of cells to be cleared in is column A:
Sub ClearCells()
Dim s1 As Worksheet, s2 As Worksheet
Dim N As Long, I As Long, addy As String
Set s1 = Sheets("test_url")
Set s2 = Sheets("main_lists")
N = s1.Cells(Rows.Count, "A").End(xlUp).Row
For I = 1 To N
addy = s1.Cells(I, 1).Value
s2.Range(addy).ClearContents
Next I
End Sub

Resources