vba - copy data from one sheet to another due to condition - vba

I am very new to vba (and code in general) so I apologise if I haven't asked the right question or have missed a thread that covers this. I have spent a couple of weeks trying to find the answer so hopefully you may be able to help.
I am trying to copy, data from one sheet (Named Master Sheet) to another depending on a variable in column L (Variables "In Progress" or "Not Started") to an Overview / GUI sheet. My current code (below) does this for the first line of data, however I would like this to work for the whole sheet.Unfortunately it will have a changing amount of data added so the array will be expanding- unsure how much more difficult this will make it.
Thank you very much for any help you can provide, and I apologise for the marked out notes. I can add a picture too (if possible) if it would help make more sense of what I would like to do?
Sub Update_Uncompleted_Tasks()
' Update_Uncompleted_Tasks Macro
' Selects tasks from Master Sheet and copies to the Overview Sheets if assigned as uncompleted
'DON'T USE BELOW YET (UNSURE IF IT WILL WORK)
'Maybe Vlookup?
'Dim LastRow As Long, i As Long
'LastRow = Cells(Rows.Count, "L").End(xlUp).Row
'For i = 1 To LastRow
Sheets("Master Sheet").Select
If Range("L2") = "In Progress" Then
Range("A2:L2").Select
Selection.Copy
Sheets("Overview").Select
Application.Goto Reference:="R10000C2"
Selection.End(xlUp).Select
Selection.Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ElseIf Range("L2") = "Not Started" Then
Range("A2:L2").Select
Selection.Copy
Sheets("Overview").Select
Application.Goto Reference:="R10000C2"
Selection.End(xlUp).Select
Selection.Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
'Next i
End Sub

First of all you should take a look at this: Avoid using select in Excel-VBA-Macros.
The following code should fulfill your needs, but it requires that your data in column L has no empty cells (until the end is reached)
Sub Update_Uncompleted_Tasks()
Dim row as Long
'Initial value
row = 2
With ThisWorkbook.Worksheets("Master Sheet")
Do Until IsEmpty(.Range("L" & row))
If (.Range("L" & row).Value = "In Progress") Or (.Range("L" & row).Value = "Not Started") Then
.Range("A" & row & ":L" & row).Copy
ThisWorkbook.Worksheets("Overview").Range("B10000").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
row = row + 1
Loop
End With
End Sub
The loop ends when a row is reached where the cell in column L is empty.
EDIT: You can also replace the Do Until -- Loop with a For row=2 To lastRow -- Next row. To determine the last row of your data, there are many ways, check out this link Excel-VBA find last row or just use the search function.

You can use this piece of code to get the number of last nonempty line on your sheet:
Dim LastDataLine As Long
LastDataLine = Sheets("Master Sheet").Range("A" & Rows.Count).End(xlUp).Row
And for last non-empty column (just in case):
Dim LastDataCol As Integer
LastDataCol = Sheets("Master Sheet").Cells(1, Columns.Count).End(xlToLeft).Column
If you also need help implementing a loop which goes through each line leave a comment.

Related

Creating a record of data in excel

Currently I have an excel sheet that works out certain prices which change everyday. I would like to have a vba button that records everyday's prices for reference, saving the last price of the data everyday (I update the price frequently during the day)
I wrote the code below but seem to be getting the error:
Compile error: Invalid Qualifier
[on the first LastRow.Offset() line]. I am quite new to vba and so any help would be appreciated
Private Sub CommandButton1_Click()
'Selecting the data to copy
Range("C23:O23").Select
Selection.Copy
'Find the last used row in Column B
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
'if still today, replace data, if not record the data on the next line
If LastRow = Date Then
LastRow.Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats,
Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Else
LastRow.Offset(1, 0) = Date
LastRow.offset(1, 1).Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats,
Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
End Sub
UPDATE: So, Ive changed a bit of my code where I define the LastRow variable differnetly:
Dim LastRow As Range
Set LastRow = Range("B31").End(xlDown)
This seemed to lead to a different error, "1004", in the line just after the else statement
LastRow.Offset(1, 0).Value = "=today"
Any advice will be appreciated
LastRow is defined as Long
Dim LastRow As Long
And then you are trying to use an Offset method, which is only available on Range objects.
Make the following changes and you should be good to go.
Dim LastRow As Range
With ActiveSheet
Set LastRow = .Cells(.Rows.Count, "B").End(xlUp)
End With
Reading this post on how and why to avoid select will take you far too. The code above can be optimized to work much smarter.
Looks like you have a typo in your else statement:
LastRow.oofset(1, 1).Select

VBA- Why End(xlDown) will take me to the very bottom of my excel

The assignment requires me to run the Monte Carlo result 1000 times. I already create a row of 30 years values(B5:AE5), and I want to repeat the process 1000 times. Every time, there will be a new row comes out, and all the values will be random.
Below is my code, for some reason, it will go to the very bottom of my excel sheet. I want the second row of 30 years values inside (B6:AE6).
Sub Macros()
Dim trail As Long
trail = InputBox("Enter the number of time you want to simulate this Macros", "Macros", "10")
For i = 1 To trail
Application.CutCopyMode = False
Range("B5").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Selection.End(xlDown).Select
Selection.Offset(-1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A4").Select
Selection.End(xlDown).Select
Selection.Copy
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Application.CutCopyMod = False
Next i
Range("B4").Select
End Sub
Thank you sooo much!
To answer your question about why your End(xlDown) takes you to the end of the sheet, the Selection.End(xlDown).Select is similar to pressing Ctrl+Down on the spreadsheet. (Likewise Selection.End(xlToRight)).Select is similar to pressing Ctrl+Right.)
Hence if you are on an empty sheet, or if all the cells beneath the active (or referenced) cell are empty, then pressing Ctrl+Down will bring you to the last row.
All that said, you can avoid that whole issue and improve your code significantly by
Removing all the Select statements and work directly with the range objects.
Using the defined range (B5:AE5) since you know what it is.
Just using the counter to resize the range to to paste the values and formats (and eliminate the loop).
See the code below:
Sub Macros()
Dim trail As Long
trail = InputBox("Enter the number of time you want to simulate this Macros", "Macros", "10")
With Range(Range("B5"), Range("AE5"))
.Copy
.Offset(1).Resize(trail - 1, 30).PasteSpecial xlPasteValues
.Offset(1).Resize(trai1 - 1, 30).PasteSpecial xlPasteFormats
End With
With Range("A5")
.Copy .Offset(1).Resize(trail - 1)
End With
'if you don't need to copy the formats you can change the above With statements to just this:
'With Range("A5:BE5")
' .Offset(i).Resize(trail - 1,31).Value = .Value
'End With
End Sub
It sounds like you want to place formulas in the selected number of rows.
Sub Frmla()
Dim i As Long
i = InputBox("enter Number")
Range("B6:AE" & 5 + i).FormulaR1C1 = "=R[-1]C*0.7"'whatever the formula is
End Sub

VBA to Copy and Past into next blank cell within a set range

I have the below vba code created to copy and paste data. The report I'm creating captures historical data to be updated every hour. I need to be able to paste into the next available cell below B10 but cannot figure out how to do that, any suggestions? Thanks!
Range("A7").Select
Selection.Copy
Range("B10").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
The code assumes that you want the value in cell "A7" to be sent to the first available(blank) cell below B10:
Sub Next_Available()
Dim nextAvailableCell As Long
nextAvailableCell = Application.WorksheetFunction.Max(Cells(Rows.Count, "B").End(xlUp).row + 1, 11)
Range("B" & nextAvailableCell) = Range("A7")
End Sub

Trying to use Excel VBA to copy/paste rows onto form, saving form in between rows

I have a workbook that serves as source data for another Excel-based form (not a Userform, just a formatted spreadsheet). The source file has anywhere from 2-40 rows of data - starting from row 18 - and each row needs to be copied into the form and saved separately, i.e. 15 rows from the Source file equates to 15 distinct Form files.
Each cell within the row must be copied separately and pasted to specific cells on the Form. The Source form contains Clients and their relevant info. I am trying to use a macro on the Form to automatically pull line items from the Source file, save the Form as the client's name in a specified folder, and continue until a blank row is reached on the Source file. I have some basic VBA experience, but have little knowledge of loops, variables, or functions, which seem to be my best course of action here.
Here's what I have so far. All I've been able to accomplish is the copy/pasting of the first row from the Source file.
Range("B18").Select
Selection.Copy
Windows("Form.xls").Activate
Range("F7:K7").Select
ActiveSheet.Paste
Windows("Source.xls").Activate
Range("C18").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Processing Form.xls").Activate
Range("D8").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("Source.xls").Activate
Range("D18").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Processing Form.xls").Activate
Range("H29").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("Source.xls").Activate
Range("E18").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Processing Form.xls").Activate
Range("E29").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("Source.xls").Activate
Range("F18").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Processing Form.xls").Activate
Range("D33").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range(“F7:K7”).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWorkbook.SaveAs
I can't even get my macro to save the Form by the client's name. I also know that my extensive use of "Range" and "Select" will slow my code down to a crawl, I just don't know how to make it more efficient. I've tried using a reference cell to that tells the macro which row of the Source file to copy but haven't had any luck down that road either. Any and all help will be greatly appreciated!
Here's a simple demo:
Note: Not Tested
Option Explicit
Sub CopyToForm()
Dim wbSource As Workbook, wbForm As Workbook
Dim wsSource As Worksheet, wsForm As Worksheet
Dim formpath As String, foldertosavepath as string
Dim lrow As Long, i As Integer
Set wbSource = Thisworkbook '~~> assuming you write your code in Source.xls
Set wsSource = wbSource.Sheets("NameOfYourSheet") '~~> put the source sheet name
'~~> put the path where your form template is saved here
formpath = "C:\Users\Username\FolderName\Processing Form.xls"
'~~> put the path where you want to save individual updated forms.
foldertosavepath = "C:\Users\Username\FolderDestination\"
With wsSource
'~~> get the number of rows with data
lrow = .Range("B" & .Rows.Count).End(xlUp).Row
If lrow < 18 Then Msgbox "No data for transfer": Exit Sub
For i = 18 to lrow
Set wbForm = Workbooks.Open(formpath) '~~> open the form
Set wsForm = wbForm.Sheets("Sheetname") '~~> put the form sheet name
'~~> proceed with the copying
.Range("B" & i).Copy: wsForm.Range("F7:K7").PasteSpecial xlPasteValue
.Range("C" & i).Copy: wsForm.Range("D8").PasteSpecial xlPasteValues
.Range("D" & i).Copy: wsForm.Range("H29").PasteSpecial xlPasteValues
.Range("E" & i).Copy: wsForm.Range("E29").PasteSpecial xlPasteValues
.Range("F" & i).Copy: wsForm.Range("D33").PasteSpecial xlPasteValues
'~~> Save the form using the client name, I assumed it is in B?
wbForm.SaveAs foldertosavepath & .Range("B" & i).Value & ".xls"
wbForm.Close True
Set wbForm = Nothing
Set wsForm = Nothing
Next
End With
End Sub
In above code, I assumed that Form.xls is the same as Processing Form.xls.
This should give you the logic.
I hope this get's you started.
This is not test as I've noted, so if you encounter errors, comment it out.
You are frequently activating the workbooks. that's your code slows down..Below code will work faster
Sub test()
Dim dwb As Workbook
Dim swb As Workbook
Set dwb = Workbooks("Form.xls")
Set swb = Workbooks("Source.xls")
Set awb = Workbooks("Processing Form.xls")
With swb
.ActiveSheet.Range("B18").Copy Destination:=dwb.Sheet1.Range("F7:K7")
.ActiveSheet.Range("C18").Copy Destination:=awb.Sheet1.Range("D8")
.ActiveSheet.Range("D18").Copy Destination:=awb.Sheet1.Range("H29")
.ActiveSheet.Range("e18").Copy Destination:=awb.Sheet1.Range("E29")
.ActiveSheet.Range("F18").Copy Destination:=awb.Sheet1.Range("D33")
End With
End Sub
This might help steer you in the right direction:
Dim i As Long
For i = 1 To 10
With Range("A" & i)
.Copy Workbooks("ToWorkbook.xlsx").Worksheets("Sheet1").Range("B" & i + 9)
.Copy Workbooks("ToAnother.xlsx").Worksheets("Sheet2").Range("C" & i + 8)
.Copy Workbooks("AnotherOne.xlsx").Worksheets("SheetA").Range("D" & i + 2)
End With
Next i
i To 10 is used as a counter to loop through the rows in the source workbook.
For each i, you're taking the range from column A (i.e., with this, do something), copying and pasting it into different cells in different workbooks. In the first round, Range("A1") is being copied into 3 different workbooks at Range("B10"), Range("C9") and Range("D3"), respectively. The next turn, Range("A2") from the source book is going to be copied and pasted into the same destination workbooks from last time, but in Range("B11"), Range("C10") and Range("D4"). It's just a matter of finding the pattern for the different forms you need to paste into.

how do I copy same columns which are laterally placed from different worksheets into a single worksheet?

I have 50 worksheets in a workbook. columns a,b,c,d are same as columns e,f,g,h, but both sets might have different number of rows/observations. I need to consolidate all in a single sheet having only 3 columns. I need to append the column names, start copying and pasting (values) from 3rd row onwards (till end of data). I tried recording a macro too but in that case, I have to go through all the sheets manually. Can someone lead me to the right direction? I'm very new to VBA and a little help will be much appreciated. My recorded macro for copying 2 sheets goes like this:
Sheets("page 9").Select
Range("A3:D3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets.Add After:=Sheets(Sheets.Count)
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlDown).Select
Range("A67").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("page 9").Select
Range("E3:H3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlDown).Select
Range("A132").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("page 10").Select
Range("A65").Select
Selection.End(xlUp).Select
Range("A3:D3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlDown).Select
Range("A197").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("page 10").Select
Range("E3:H3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlUp).Select
Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "Date"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Type"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Size"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Discount"
Range("A1").Select
End Sub
I doubt that anyone can decypher this code; certainly I lack the ability.
The Macro recorder is a great way of learning the syntax of new commands but it does not produce "good" code. It does not know your objective and records every little step as you do it.
Take the time to study Excel VBA. Search the internet for "Excel VBA Tutorial" or visit a good library or bookshop and select an Excel VBA Primer. There are many to chose from so I am sure you will find something that suits your learning style. This study will quickly repay your investment.
Look through the excel-vba questions on StackOverflow. Many, perhaps most, will be of no current interest to you. But some will show techniques you did not know about but which will be useful. Perhaps the most difficult aspect of learning VBA is discovering what is possible. Once you know statement X exists, you can look it up and study its syntax and functionality.
Below are four macros that demonstrate relevant code. Copy them to a workbook and try them. You could not have learnt how to write these macros from a study of macro recorder output.
A This macro outputs the name of every worksheet to the Immediate Window.
Sub A()
Dim InxWsht As Long
For InxWsht = 1 To Worksheets.Count
Debug.Print Worksheets(InxWsht).Name
Next
End Sub
B This adds a new worksheet at the end of the current list and names it "Consolidate". It then creates a bold, coloured header line.
Range(CellId).Value is one way of accessing a cell's value. I have used "A1" as the cells's Id but this is just a string and could have been built at runtime. Cells(RowId, ColId).Value is another way. RowId must be a number or an integer variable. ColId can be a number, an integer variable or a column letter. I suggest you be consistent and not mix and match as I have.
I show two method of specifying a range so I can set the entire header row bold and coloured in single statements.
If I have written Range("A1").Value = "Date" this statement would have operated on cell A1 of the active worksheet. The . before Range means this statement operates of cell A1 of the worksheet identified in the With statement. Using With means I do not have to switch worksheets using Select which is a slow command.
Sub B()
Dim WhshtCons As Worksheet
Set WhshtCons = Sheets.Add(After:=Sheets(Sheets.Count))
WhshtCons.Name = "Consolidate"
With WhshtCons
.Range("A1").Value = "Date"
.Cells(1, 2).Value = "Type"
.Cells(1, "C").Value = "Size"
.Cells(1, 4).Value = "Discount"
.Range("A1:D1").Font.Bold = True
.Range(.Cells(1, 1), .Cells(1, "D")).Font.Color = RGB(0, 128, 128)
End With
End Sub
C This outputs the value of Cell A1 of every worksheet except "Consolidate".
Sub C()
Dim InxWsht As Long
For InxWsht = 1 To Worksheets.Count
If Worksheets(InxWsht).Name <> "Consolidate" Then
With Worksheets(InxWsht)
Debug.Print "Cell A1 of Worksheet " & .Name & " contains [" & _
.Cells(1, 1).Value & "]"
End With
End If
Next
End Sub
D I will not explain this macro because it is somewhat more advanced than the others. It demonstrates moving columns of data from all the other worksheets to worksheet "Consolidate". I doubt this is close to what you seek but it demonstrates that what you seek is possible.
Sub D()
Dim ColConsCrnt As Long
Dim InxWsht As Long
Dim RowLast As Long
Dim WhshtCons As Worksheet
ColConsCrnt = 1
Set WhshtCons = Worksheets("Consolidate")
WhshtCons.Cells.EntireRow.Delete
For InxWsht = 1 To Worksheets.Count
If Worksheets(InxWsht).Name <> "Consolidate" Then
With Worksheets(InxWsht)
RowLast = .Cells(Rows.Count, "A").End(xlUp).Row
WhshtCons.Cells(1, ColConsCrnt).Value = .Name
.Range(.Cells(1, "A"), .Cells(RowLast, "A")).Copy _
Destination:=WhshtCons.Cells(2, ColConsCrnt)
End With
ColConsCrnt = ColConsCrnt + 1
End If
Next
End Sub
Welcome to programming. I hope you find it as much fun as I do.