Copy and paste data from different worksheet to another worksheet in a same excel spreadsheet - vba

Sub Save7()
Dim NextRow As Range
Set NextRow = Range("AC" & Sheets("Sheet1").UsedRange.Rows.Count)
Sheet3.Range("AC14:AG14").Copy
Sheet1.Activate
NextRow.PasteSpecial Paste:=xlValues, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
End Sub
My purpose of this code is to copy data ( Five columns of 'NO' in AC14 to AG14) from sheet 3 and paste to sheet 1 where the last active cell is at.
The code above is working well, however I made some modification to the sheet tab name for sheet 1. Sheet 1 is now called "Equipment stuffs", while sheet 3 name is remaining unchanged.
After those changes, the macro stopped working. The cause is probably because I don't know how to declare "Equipment stuffs" in the code .

There's no need to do copy/paste to move data from one place on the spreadsheet to another. You should simply assign the Value of the respective Range objects, for example:
Sheet1.Range("NamedRange2").Value = Sheet1.Range("NamedRange2").Value
Also, use code names for the sheets, instead of Sheets("SheetName"), and defined named for the ranges, instead of Range("AC14:AG14", otherwise your code will stop working if the user renames the sheet or inserts or deletes any rows above your reference.

If you want to automate this a little you could collect the active workbook and loop through each sheet using wb.Worksheets. Then collect the name with targetSheet.Name.
Option Explicit
Public Sub getSheet()
Dim wb As Workbook
Dim targetSheet As Worksheet
Set wb = ActiveWorkbook
For Each targetSheet In wb.Worksheets
Debug.Print targetSheet.Name
Next targetSheet
End Sub

I’m brazilian hehe, I understood your question , I’ve a code for alter the data in same worksheet (I’ll attach it here), for you to change the data in another worksheet, you need put on:
Worksheets("NameWorkSheet) Activate
for the VBA that’s refers to this tab.

Related

ms-Excel Worksheet transfer between worksbooks and vlookup

I have a simple problem(at least seems to be) that I just cannot seem to be able to find a good solution to:
I have 4 workbooks, that all contain two of the exact worksheets(rest of the worksheets are unique for each workbook). I am storing these two worksheets in a seperate workbook(so 5th workbook). Out of these 2 worksheets, 1 of them is a Data sheet made up of many tables, which I do updates on and the other one is a sheet called V, which just uses some vlookup functions to bring up the related data from this Data sheet.
I am trying to find a way to be able to pass along this data sheet to each individual workbook, instead of editing the data sheet individually for each workbook(All 4 of them).
I was able to come up with the following macro, which checks if the sheet already exists and if it does it deletes it. Then it opens up location of the excel file, copies this worksheet to the workbook and therefore I have the most "updated" version of this data worksheet.
Sub UpdateT()
Sheets("data").Visible = True
Dim wb As Workbook
Dim aw As Workbook
''Open 2nd Workbook
Set aw = Application.ActiveWorkbook
'Check if data worksheet exists, and if it does delete it
If Not GetWorksheet("data") Is Nothing Then
Application.DisplayAlerts = False
Worksheets("data").Delete
Application.DisplayAlerts = True
End If
'Check if T worksheet exists, and if it does, delete it
If Not GetWorksheet("T") Is Nothing Then
Application.DisplayAlerts = False
Worksheets("T").Delete
Application.DisplayAlerts = True
End If
Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu001\Desktop\Update.xlsx")
'Copy To Different Workbook
wb.Sheets("data").Copy _
After:=aw.Sheets("Data1")
wb.Sheets("5120 TI").Copy _
After:=aw.Sheets("MENU5120")
'Close 2nd Workbook
aw.Save
wb.Close
'Hide the data worksheet
aw.Sheets("data").Visible = False
End Sub
'Function to check if worksheets exist
Function GetWorksheet(shtName As String) As Worksheet
On Error Resume Next
Set GetWorksheet = Worksheets(shtName)
End Function
The problem is the following:
When the new Data worksheet is transferred, the V worksheet is no longer working with the Vlookup function to be able to point to the relative information. So then I thought, okay what if I transfer BOTH Data and V worksheets, however that also did not work.
Is there a way to be able to use Vlookup, while copying the Data sheet? (The name is exactly the same I do not understand why it does not seem to be able to point to the cells of the table). It just looks blank, can't point to anything.
NOTE: I am not changing the format of the Data tables, basically just the values, so the format is the exactly the same.
It is probably important to note that the main excel workbooks(the 4) are in use 24/7, therefore I cannot go the other way(Update from Data workbook to the main workbook). I must "pull" the updated worksheet rather than "push".
If anyone has any suggestions I'd really appreciate. Thank you.

code won't work across multiple worksheets (Tried moving selection, select, etc. and still wont work)

An Excel VBA newbie here. I am working on this code for a one-click-for-all worksheets macro. So the idea is to have a macro that once clicked, can trigger the IF-ISERROR-Vlookup formula in multiple worksheets (around 12 now, but will keep increasing in the future). Both the formula and the result are displayed in the same columns in multiple worksheets, but of different number of rows (Sheet 1 col B[data] and C[formula], sheet 2 Col B and C, etc.)
Now the code I did below works only when I go to a worksheet and trigger the macro in that specific worksheet; which means I have to do it one by one per sheet.
I tried removing the select, the selection and the activesheet as recommended in previous posts, but it showed an error message to me.
So my questions are:
a) How can I modify the code so that I can create a macro that triggers all worksheets in one click?
b) As you can see below, I put Range("C4:C54") even though the number of rows are different in every sheet, because I have no idea how to make the range cover different rows only until it hits the last cell with values.
Dim ws As Worksheet
For Each ws In Worksheets
Range("C4").Select
ActiveCell.FormulaR1C1 = _
"=IF(ISERROR(VLOOKUP(RC[-1],TestScore,1,FALSE)),""Pass"",""Fail"")"
Range("C4").Select
Selection.AutoFill Destination:=Range("C4:C54")
Range("C4:C54").Select
Next ws
End Sub
Anybody can help with this problem? Any help would be appreciated. Thanks so much beforehand!
Edit:
Added the sample snapshot of the problem as requested
Put this code in the Module (Insert >> Module):
Dim ws As Worksheet, LastRow As Long
For Each ws In Worksheets
With ws
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Change the number (1) with appropriate column
.Range("C4:C" & LastRow).FormulaR1C1 = "=IF(ISERROR(VLOOKUP(RC[-1],TestScore,1,FALSE)),""Pass"",""Fail"")"
'The formula will be filled down til the last row
End With
Next ws
Avoid using Select statements - it can cause issues and instead refer to the cells explicitly. This will insert your formula in cells C4 to the last cell in that column
Dim ws As Worksheet
For Each ws In Worksheets
With ws
.Range("C4:C" & .Cells(.Rows.Count, "B").End(xlUp).Row).FormulaR1C1 = _
"=IF(ISERROR(VLOOKUP(RC[-1],TestScore,1,FALSE)),""Pass"",""Fail"")"
End With
Next ws

Copy and moving an entire sheet to another workbook. 1mil rows to 65536 rows

The following is part of my code that involves copying an entire named sheet from one master file to a new unsaved file that's being worked on:
ActiveWorkbook.Sheets("VehicleList").Copy _
After:=Workbooks(2).Sheets(1)
So this worked fine to place the sheet into workbook 2 but now the files we're dealing with are in old excel mode which is throwing up the following error due to old excel having less rows:
"Excel cannot insert the sheets into the destination workbook, because it contains fewer rows and columns"
How can I tweak the copy and pasting into Workbooks(2) without breaking the code? I thought defining a range of 1000 rows to copy and move would work, but this also gave an error. Thanks for your help.
Assuming you just want the values (i.e. I'm speeding it up by not doing a copy paste) you can do:
Workbooks(2).Sheets.Add After:=Sheets(1)
Workbooks(2).Sheets(2).Range("A1:F1000").Value = ActiveWorkbook.Sheets("VehicleList").Range("A1:F1000").Value
I'd go like follows
Option Explicit
Sub main()
Dim targetWs As Worksheet
With Workbooks("MyWorkbookname").Sheets("VehicleList") '<--| fully qualify reference wanted worksheet in the wanted workbook
Set targetWs = SetOrGetSheet(Workbooks(2), .name) '<--| get the (new) target worksheet on the target workbook named after referenced sheet
Intersect(.Range("A1:F1000"), .UsedRange).Copy targetWs.Cells(1, 1) '<--| copy range to target worksheet on the target workbook
If targetWs.name <> .name Then MsgBox "a new sheet has been created in " & targetWs.Parent.name & " with name " & targetWs.name
End With
End Sub
Function SetOrGetSheet(targetWb As Workbook, shtName As String) As Worksheet
targetWb.Worksheets.Add '<--| add a new sheet in the target workbook
On Error Resume Next
Set SetOrGetSheet = targetWb.Worksheets(shtName) '<--| try and get any possible target workbook sheet with the passed name
If SetOrGetSheet Is Nothing Then targetWb.ActiveSheet.name = shtName '<--| if target workbook has no worksheet with passed name then name the new one after it
Set SetOrGetSheet = targetWb.ActiveSheet 'return the new worksheet
End Function
should you be afraid your range-to-copy could exceed 65 rows and/or 256 columns than you should add its size check
edit for values pasting only
should you be interested in pasting values only then you can go like follows:
Sub main()
SetOrGetSheet(Workbooks(2), "VehicleList").Range("A1:F1000").value = ActiveWorkbook.Sheets("VehicleList").Range("A1:F1000").value '<--| copy values form source to target worksheet
End Sub
while SetOrGetSheet() function stays the same as above
as you may have guessed that function is there for a more general approach where you may want (or just have) to handle the possibilty of target workbook having a worksheet named after "VehicleList" already

Copying until last row

I have multiple sheets and I want to copy their data to another workbook on the last empty row of it. The data has a random number of rows but a defined number of columns, and I am having trouble copying it (not all the sheet, only the rows that have data) and then pasting it to the last row of the final workbook. How should I do it? I have no clue at all...
Disclaimer: I don't want to use select of activesheet as I will have multiple workbooks open and this has brought me problems. Also, the data is continues, and in this I mean that there are no empty rows in the middle of it. Also, I don't think this will change anything but this code is running inside a loop so it copies all sheets from multiple files.
Thanks!
col is the column number you're trying to copy
For Each ws in Activeworkbook.worksheets
lastrow = ws.cells(ws.rows.count, col).end(xlup).row
'code to copy and paste
Next ws
I asume you have a handle to the worksheets, so you can use this code to copy the data:
Public Sub CopyAcross(oSheetFrom As Worksheet, oSheetTo As Worksheet)
Const DATA_START_ADDRESS As String = "$A$1"
oSheetFrom.Range(DATA_START_ADDRESS).CurrentRegion.Copy
oSheetTo.Range("A" & oSheetTo.Rows.Count).End(xlUp).PasteSpecial xlPasteAll
Application.CutCopyMode = False
End Sub
Assuming that the data to be copied has the same start address on each sheet, which is specified as DATA_START_ADDRESS

Copy appended data to a different worksheet

I have the following which is working in the same workbook how do I get this to use a summary sheet in a different workbook?
Sub SummurizeSheets()
Dim ws As Worksheet
Application.ScreenUpdating = False
Sheets("Summary").Activate
For Each ws In Worksheets
If ws.Name <> "Summary" Then
ws.Range("D2:D6, D8:D15").Copy
Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).PasteSpecial (xlPasteValues)
End If
Next ws
End Sub
Make sure you place the sub-routine in a Module, and not in
ThisWorkbook. You can insert a new module by right-clicking on workbook name (from the VBA editor) and going to Insert > Module.
Make sure the workbooks you want to use/reference are open.
Make sure the workbooks are all located in the same workbook collection. This is not a problem unless you manually create an additional instance of Excel.
Reference the workbooks using the Workbooks() object just like you
do with Worksheets.
Sub test()
Dim b2 As Workbook 'We will use this variable as a reference to the external workbook that contains the "Summary" worksheet.
Set b2 = Excel.Workbooks("testbook2") 'We assign the external workbook (which I named "testbook2" for the purposes of this example) to our 'b2' variable.
Dim ws1 As Worksheet
Dim ws2 As Worksheet 'We will use these variables as references to the worksheets we're using.
Set ws1 = Excel.ActiveSheet 'We set ws1 to equal our current sheet (which presumably is where you'll be copying data from).
Set ws2 = b2.Worksheets("Summary") 'We set ws2 to equal the sheet (named "Summary") in the external workbook (named "testbook2").
ws1.Range("D2:D6").Copy 'We copy the data from the active sheet, which we reference using our 'ws1' variable.
'Note: I had issues with using multiple ranges in the same object so I removed this from your code.
ws2.Cells(Rows.Count, 4).End(xlUp).PasteSpecial xlPasteValues 'You only need to use the ws2 variable since we've already defined it as the "Summary" sheet you want.
End Sub
I'm not sure why I follow that first rule, but I seem to remember having issues when using ThisWorkbook in conjunction with external workbook references.
Update
I edited the code to show you a better example of how to do this. You almost never need to use "Activate" or "Select" commands in VBA. Just assign variables and reference the values directly.