For Next loop with two statements - Copy & Paste - vba

I have a workbook with 2 worksheets, the 1st having a large range of data and formulas and the 2nd containing two empty tables to be populated with specific date from sheet1. Sheet1 has a column of dates Range("DK7:DK39") that range from 5/1/1986 to 5/1/2018. Any time the first date is changed in this column ("DK7"), all of the other dates in the following years will auto-update to the same day in the given year. With these changes, two separate columns will be repopulated with new data that is determined based on date-specific data.
I am trying to run a code that will loop through a range of days for which I need data (5/1 through 8/28), changing the value of cell("DK7") to each date in that range. However, I need the loop to also copy and paste data from the two data columns ("DS7:DS38") & ("DT7:DT38") into the two tables on sheet2 which have the years 1986-2017 as the y-axis column and 5/1 through 8/28 as the x-axis row. I have figured out how to loop the date through the Cell("DK7") but can't figure out the copy & pasting into the 2nd worksheet in respective year / date columns. Any help greatly appreciated, thanks.
Private Sub CommandButton1_Click()
Dim i As Date
For i = ("5/1/1986") To ("8/28/1986")
Range("DK7").Value = i
Worksheets(1).Range("DS7:DS38").Copy
Worksheets(2).Range("D4:E36").PasteSpecial
Next i
End Sub

This is a good way to loop through the dates:
Public Sub TestMe()
Dim i As Date
For i = DateSerial(1986, 5, 1) To DateSerial(1986, 8, 28)
Debug.Print i
Next i
End Sub
Make sure you are using DateSerial() function as there is a big difference between date formats around the world.

Related

VBA: Finding the row number by looking up a user defined value (date)

I am trying to use VBA to look up the row value that corresponds to a user defined date on one of my work sheets so that I am able to edit all data on that row.
As a bit of context:
I have several time series data sets that all have different start and end dates with a good portion of overlap in the middle. I want to chart these using user defined date parameters, however, because of non-uniform start dates, the chart is impossible to dynamically rebase.
I was hoping to use a macro to clone the data on one sheet, overwrite the line of values that corresponds to the user defined start date, and then calculate return values based on percentage change figures (I already have in a different sheet).
If I can dynamically o/w the row that corresponds to the UD start date of the date range, I can replace it with a one and all my calculations will effectively rebase.
Any and all feedback would be great!
EDIT
Lucas,
I am having two issues; firstly, what I have inexpertly cobbled together doesn't work when I protect the sheets (not insurmountable); secondly, it doesn't work :). Here is my work:
Sub Rebase()
Dim UDStartVal
Dim UDStartLoc As Range
Dim UDRow As Integer
'
' Rebase Macro
' A macro to rebase the chart to the user defined start date.
'
'
Sheets("Cumulative Monthly Returns").Select
Cells.Select
Selection.Copy
Sheets("Chart Numbers").Select
Range("A1").Select
ActiveSheet.Paste
' Lookup to change the value of the cells corresponding to the user defined start date to 0, effectivley rebasing the portfolo.
Worksheets("Cumulative Period Returns").Activate
UDStartVal = Cells(4, 2).Value
Set UDStartLoc = Range("A:A").SpecialCells(xlCellTypeVisible).Find(UDStartVal)
Set UDRow = UDStartLoc.Row
Stop
End Sub
Here's some code that I use to find the row of an entry based on quote numbers on a sheet that gets resorted and re-filtered constantly.
Private Sub FindQuote(partNum as String)
Dim quoteRow as Range
Set quoteRow = Range("A:A").SpecialCells(xlCellTypeVisible).Find(partNum)
then when I want to do something that uses the range of that row I use quoteRow.Row
If Not quoteRow Is Nothing Then
quoteNum = Cells(quoteRow.Row, "P").Value
Cells(quoteRow.Row, "Q").Value = "Found"
Else
MsgBox "No quote was found"
End If
End Sub
Did you need help with the part where you clone your sheet?

Excel Macro To Advance Date

I have a ton of excel sheets that each have 3 excel workbook tabs. On the last one there will be a ton of data but one column will be a date column with a bunch of different dates underneath. The date format will be MM/DD/YYYY. I need to advance each date ahead by 4 years.
I imagine that I will need to select the correct workbook, search for the particular column, and then loop to iterate through each value underneath that column to advance it, but the day itself needs to stay the same. For example, if its 10/05/2017, it needs to be 10/05/2021. Any suggestions or help would be great. Thank you in advance.
Thank you for the help, I realize I wasn't very helpful at all with my question. I'm very new to VB script and excel macros in general. I hadn't gotten how to search for the column itself as I would like it find the column no matter what the column value is (possibly search for a cell that says "Date" through the entire sheet?, I was just trying to add the 4 years to start with and couldn't find the function I needed. This is what I had from what I derived and seems like this is very wrong ha.
Do Until IsEmpty(ActiveCell)
Set ThisCell = ActiveCell
ThisCell = DateAdd("yyyy", 4, ColumnValueHere)
' Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select
Loop
You'll be wanting the DateAdd function
Try something like this:
Sub AddDates()
Dim lastRow as integer
Dim theSheetImWorkingOn as worksheet
Dim theColumnNumberForTheDates as integer
theColumnNumberForTheDates = 5 ' change this to be the column number you want
Set theSheetImWorkingOn = Sheets("Put your sheet name here")
lastRow = theSheetImWorkingOn.Cells(1000000, theColumnNumberForTheDates ).End(xlUp).row
For x = 2 to lastRow ' assuming your data starts on row 2
theSheetImWorkingOn.Cells(x, theColumnNumberForTheDates) = DateAdd("yyyy", 4, theSheetImWorkingOn.Cells(x, theColumnNumberForTheDates))
Next x
End Sub

How to select column and display its current format using VBA Macro?

Please find my requirement below for which I am unable to find any solution:
1. Iterate over workSheet from workbook
2. Find all the columns containing date values using current format/type of column (Here is a trick. Worksheet is not static, it can contain any number of columns containing date values. Columns containing date values may have any name. And such worksheets can be more than one in number)
3. Apply macro on date columns for date formatting (below macro) if "Flag" value is "y"
<code>
Sub FormatDate()
If wksSecDist.Range("Flag").value = "y" Then
LastRowColA = Range("X" & Rows.Count).End(xlUp).Row
' Here I am finding total number of rows in column X
wksSecDist.Range("X2", "X" & LastRowColA).NumberFormat = "dd/mmm/yyyy"
' Here applying specified date format to Range("X2", "X10") [if last row index for column X is 10]
End If
End Sub
</code>
I am just a beginner to VBA.
Thanks in advance.
I suspect you didn't find a solution on the internet because you looked simply for a solution and not the parts needed to build your own solution.
You mention you are a VBA beginner, please take the below answer to be of educational use and begin you in getting you where you need your tool to be. Note, if it doesn't answer your question because of information that was not included, it has still answered your question and the missing information should form part of a new question. That said, lets get this function up and running.
From what you have written I have interpreted the requirement to be: -
Look over all worksheets in a workbook ('worksheets can be more than one in number')
Check every column to see if it holds a date value
If it does, set the whole column to a specific format
What is needed to accomplish this is iteration(loops), one to loop through all worksheet, and another to loop through all columns: -
The is pseudo code of the target: -
.For each Worksheet in the Workbook
..For each Column in the Worksheet
...If the Column contains dates then format it as required
..Process next column
.Process next Worksheet
We achieve this using a variable to reference a Worksheet and using a loop (For Each) to change the reference. The same goes for the columns.
Public Sub Sample()
Dim WkSht As Excel.Worksheet
Dim LngCols As Long
Dim LngCol As Long
'This loop will process the code inside it against every worksheet in this Workbook
For Each WkSht In ThisWorkbook.Worksheets
'Go to the top right of the worksheet and then come in, this finds the last used column
LngCols = WkSht.Range(WkSht.Cells(1, WkSht.Columns.Count).Address).End(xlToLeft).Column
'This loop will process the code inside it against every column in the worksheet
For LngCol = 1 To LngCols
'If the first cell contains a date then we should format the column
If IsDate(WkSht.Cells(2, LngCol)) Then
'Set right to the bottom of the sheet
WkSht.Range(WkSht.Cells(2, LngCol), WkSht.Cells(WkSht.Rows.Count, LngCol)).NumberFormat = "dd/mmm/yyyy"
End If
Next
Next
End Sub
Hopefully that has all made sense, this does work on the premise that the header row is always row 1 and there are no gaps in the columns, but these are separate issues you can approach when you're ready to.

Copy all Rows in excel sheet only if specific cell = today's date

I'm knew to vb scripting for excel and cant seem to find code that will help do what i want. maybe its how im wording my search criteria.
Sheet 1 is an input sheet which saves data into sheet 2 every day. There is a cell that holds the current date.
So sheet 2 just collates and saves everything entered.
Each day there are several rows saved into sheet 2.
I need a button on sheet two that only selects the rows that have today's date and copies the content. I just need that data copied so i can then paste this into off clipboard into another application.
Can anyone help? im using office 2016.
Thanks
Excel VBA, How to select rows based on data in a column?
I believe this is something that would be useful for yourself since you are new to VBA code.
You will most likely need to supplement your code with the parts you ned, IE current date, only coping and not pasting and so forth.
I recommend google for those parts as it is widely avalible, I.E. VBA Excel "then what you are searching for"
Dim TodaysDate As Date
TodaysDate = Now
TodaysDate = Format(TodaysDate, "dd/mm/yyyy")
^ For instance will give you the current day in dd/mm/yyyy format
I leave the rest to you, hope this helps
I would loop through the rows in the second sheet and hide the rows not matching the date. So something similar to this:
Dim today As String
Dim Rows As Integer
Dim Sheetname As String
Dim Column As Integer
Sheetname = "Sheet2" 'Name of your second sheet
Column = 1 'Column with your date
today = Now
today = Format(today, "dd/mm/yyyy")
Rows = Sheets(Sheetname).UsedRange.SpecialCells(xlCellTypeLastCell).Row
Dim i As Integer
For i = 1 To Rows Step 1
If Sheets(Sheetname).Cells(i, Column).Value <> today Then
Sheets(Sheetname).Rows(i).EntireRow.Hidden = True
End If
Next i
Then you can copy the rows of today.
To show all rows again, simply use
Dim Sheetname As String
Sheetname = "Sheet2" 'name of your second sheet
Sheets(Sheetname).Cells.EntireRow.Hidden = False

VBA Excel - Summing a range of cells based on result in a different range of cells

I am attempting create a forecasting function in excel using based on a set of preregistered historical data. I am new to VBA and I am unable to make this function.
I have three Ranges:
Range 1 lists every day in a year. All cells are formatted in the form of "date".
Range 2 on a different sheet named "C" also lists every day in a year. All cells are formatted in the form of "date".
Range 3 on sheet "C" contains the dollar value actualized in the specific date of the year mentioned in Range 2.
Requirement:
The function should take 3 different variables which are the three different ranges. The Function should first "LOOKUP" the month and year of the selected cell and match it with the month of and (year -1) of the cells in Range two.
Accordingly, The cells in Range 3 on the same row in which the "LOOKUP" matches with Range 2 should sum up and then divide by the count of cells counted.
So far I have been able to create a function named MNAME.
Function MNAME(x As Variant) As String
Dim CurrentMonth As Date
CurrentMonth = x
MNAME = MonthName(Month(CurrentMonth), True)
End Function
But I am failing to nest the lookups and sum up the values.
you dont need VBA.
Read Up on the SUMPRODUCT() function - Here is a good explanation
to summarise your problem you want to find out:
if the year of the cells in Range2 is the same as YEAR(reference_cell)-1
--> IF(YEAR(reference_cell)-1=YEAR(Range2))
if the month of the cells in Range2 is the same as MONTH(reference_cell)
--> IF(MONTH(reference_cell)=MONTH(Range2))
where 1. IS TRUE and 2. IS TRUE, sum corresponding cells in Range3
--> =SUMPRODUCT(--(YEAR(reference_cell)-1=YEAR(Range2))*--(MONTH(reference_cell)=MONTH(Range2))*Range3)