Display last imported week - vba

I have a excel file that imports from weekly files. I can specify the number of week to import in an input box. From this number, I construct the file path and name for that specific week and then imports it.
In cell D1 I want to show the week that was last imported, so if I last Imported week 12, cell D1 should show "12" and if later later I imported a file from a older week like 4, cell D1 should show "4"
In the excel file the source files that will be imported will be trough a vba code, it don't have any type of tables in the source file, so I need to implement this in my code in order to show in the cell D1 the week that as been imported.
I tried implementing this to my code Range("D1").Value = WeekVal in order to try to fill that specific cell with the number of the week that was imported.
I searched online but the ones that I saw didn't apply very well to my code. So I don't really need a date I just need the value from the file name that represents the week, like here :
"Status 496 800 week -->12<-- 2015.xls"
that number is what I need to show in the D1

I don't know how your file's name is referenced so I did a function, here is a routine to test it :
Sub Luis_Montez()
Dim TpS As String, _
ReZ As String
TpS = "Status 496 800 week 12 2015"
ReZ = Get_WeekNb_From_FileName(TpS)
MsgBox "_" & ReZ & "_"
End Sub
And here is the function :
Public Function Get_WeekNb_From_FileName(ByVal FileName As String) As Integer
Dim TpStr As String
TpStr = Trim(Mid(FileName, InStr(1, LCase(FileName), "week") + 4, 3))
Get_WeekNb_From_FileName = CInt(TpStr)
End Function
An even easier solution that in the duplicate, just use :
Format(Date, "ww")

You are probably writing your WeekVal in the D2 cell of another worksheet (for instance the workbook you just imported your data for the week from).
To avoid this, always refer to any cell or range by explicitly naming the workbook and either the named range or the sheet name.
In your case, I advice to select the D1-cell you want to write to. Now left of your formula bar you can read D1. Fill in WeekVal instead. Then change your code to
Thisworkbook.Name("WeekVal").RefersToRange.Value = WeekVal

Related

Finding empty cell then loop to get new data

I'm have a spreadsheet that takes 31 different tabs with daily data, then summarizes it into a monthly tab, then converts each day's data into a software upload. In order to expedite my process I'm trying to combine every daily upload into another tab at once instead of copy/pasting each day manually. Currently to see the upload for each day I am changing the number in cell B3 to the day I need and it will give me the upload data.
EDIT:
How I hope this will work is the macro will put "1" in cell B3 on the Upload tab, take the data in A10:I34, paste it over to the first empty cell in column A on the Upload Files tab, then go back to the upload tab, change cell B3 to "2", copy the data in A10:I34, paste it to the next empty cell in column A on the Upload Files tab... repeat until the data from day 31 has been pasted onto the Upload Files tab.
Data is in tab called "Upload"
The only cell that can change on tab "Upload" is cell "B3"
Data range is "A10:I34"
Data needs to paste values on tab "Upload Files"
"Upload Files" has formatting data in row 1 needed for the software
EDIT:
The macro needs to looks for the next empty row after each day's data has been pasted
Loop needs to stop at day 31
My issue now is that I can't get it to go back to the upload tab and change the date to the next day and then continue with the empty cell loop. It ends up just pasting the data over the original data, or not changing the cell value to the next day. Below is what I have for changing the days.
EDIT #3: I tweaked it, it works now. Please take a look and let me know if you think it could be improved. Added For/next.
Dim Count as integer
Dim x as Long
Count = 2
For x = 1 to 30
Do While Worksheets("Upload Files").Range("A" & Count).Value <> ""
Count = Count +1
Loop
Worksheets ("Upload").Range("B3").Value = Worksheets("Upload").Range("B3").Value +1
Worksheets("Upload").Range("A10:I34").Copy
Worksheets("Upload Files").Range("A" & Count).PasteSpecial xl PasteValues
Next x
Any suggestions? Previous attempts just simply selected the exact cell where the previous data ended on the "Upload Files" tab, but adding rows in the "Upload" tab means I have to manually recalculate which cells the data will be pasted, which is about as time consuming as doing the whole thing manually.
Thanks,
I added some comments for your understanding inside the code:
Sub Test1()
Dim Count As Integer
Dim lLastRow As Long
Dim i As Long
Count = 2
' This would give you the last used row in the Sheet
lLastRow = Worksheets("Upload Files").Cells(Worksheets("Upload Files").Rows.Count, 1).End(xlUp).Row
For i = 1 To lLastRow
' You don't specify if you are trying to do anything in this section inside de Loop
' but if you just want to cound for the last row, you can remove the loop.
Next i
If Worksheets("Upload").Range("B3").Value < 32 Then
' Dont need this.
'Worksheets("Upload").Range("B3").Select
Worksheets("Upload").Range("B3").Value = Worksheets("Upload").Range("B3").Value + 1
' Here it would be nice if you specify from what Sheet you are copying this range. I guess is Upload.
Worksheets("Upload").Range("A10:I34").Copy
Worksheets("Upload Files").Range("A" & Count).PasteSpecial xlPasteValues
End If
End Sub
I guess you're after something like follows:
Option Explicit
Sub upload()
Dim targetSht As Worksheet
Set targetSht = Worksheets("Upload Files")
Dim i As Long
With Worksheets("Upload")
For i = 1 To 31
.Range("B3").Value = i
Application.Calculate
With .Range("A10:I34")
targetSht.Cells(targetSht.Rows.Count, 1).End(xlUp).Offset(1).Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
Next
End With
End Sub

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?

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

Excel - Conditional macro / VBA script

I'm trying to automate a report that for a customer and I'm a bit stuck with one of the hurdles that needs to overcome, I have some ideas but am new to VB programming.
The requirement is to copy a range of cells from one sheet to another, but the destination needs to change depending on the current date. Using a general example I'm trying to achieve the following:
If the date is the 1st of the month, the destination range is B2:F3, if it is the 2nd then the destination range is B4:F5, if the 3rd then destination is B6:F7....... if the 31st then the destination is B62:F63, the source ranges are static.
I figured I could probably achieve this by writing a huge script which contained an IF statement for each day of the month, but I was hoping I could be a bit smarter and use variables to assign the row references at the beginning of the script then just sub them back into the select/copy statements.
Absolutely you can.
Dim x as Integer
Dim daymonth as Integer
Dim rw as String
daymonth = CInt(Format(date, "d"))
x = daymonth * 2
rw = CStr(x)
Now you can use range like:
Range("D" & rw & ":F" & CStr(x + 1))
Just an example. Then since the number is constant between the two ranges just add that number to x and use it in the range.
You may want following subroutine.
Sub copyDataDependOnDatte()
Dim today As Date, dayOfToday As Integer
Dim sWS As Worksheet, dWS As Worksheet
'set two worksheets to variables
Set sWS = Worksheets("source") 'Worksheet which has data to be copied
Set dWS = Worksheets("destination") 'Worksheet which is used to record data of days.
' get day of today
today = Now() 'get date of today
dayOfToday = Day(today) ' get day of today
Range(sWS.Cells(2, 2), sWS.Cells(3, 6)).Copy 'copy B2:F3 of worksheet "source"
dWS.Cells(dayOfToday * 2, 2).PasteSpecial ' paste to worksheet "destination" at place determined by day of today
End Sub
In this code,I assumed following for writing concreat code.
"source" is name of worksheet which contains the data to be copied
"destination" is name of worksheet which records tha data copied from "source" worksheet
Data to be copied is exist at "B2:F3" of worksheet "source"
Please change worksheets' names to real names of your data.
Place of data to be copied is described as "Range(sWS.Cells(2, 2), sWS.Cells(3, 6))" in the code.
cells(2,2) means cell on 2nd row and 2nd column, i.e. "B2".
Cells(3,6) means cell on 3rd row and 6th column, i.e. "F3".
Plese correct place to fit your data.

Using a Lookup at Next Available Line in Excel VBA

I am trying to implement a lookup feature in Excel Vba. I do not have any code to share because I am uncertain how to begin with the implementation.
Upon opening a workbook I want to use VBA to enter today's date into the next available row in column A - which I currently have working now. However, at that point in Column B on that same line, I to find a stock rate in a table I have, where J2 is the date and J3 is the price of the stock.
What I think I need is a formula where I can lookup the date I just added in this table and then retrieve the price relevant to that date. I understand Vlookups in Excel very well; it is I just do understand how to use a lookup here for each next available line.
Here is my code for the dates:
Dim rnum as integer
rnum = sheet17.usedrange.cells.rows.count +1
sheet17.cells(rnum, 1).value = date
I am seeking lookup functionality relative to (rnum, 2) as the next available line.
If you want to hardcode it, that'd be
sheet17.cells(rnum, 2).formula = "=vlookup(" & sheet17.cells(rnum, 1).address(false,false,xlA1) & ", $J:$K, 2, false)"
If you would prefer to use whatever formula is on the previous line,
sheet17.range(sheet17.cells(rnum-1, 2), sheet17.cells(rnum, 2)).FillDown
I'm assuming when you say "stock rate in a table" you mean "stock rate in a worksheet" and also assume that the values in column J contain the stock rates for the same stock. In other words, you are only matching on a date in that column and not the stock symbol AND the date. (Please let me know if I have these assumptions wrong).
That being, said you can try the following formula in column B:
=IF(A50<>"",INDEX(J:J,MATCH(A50,StockSheet!J:J,0) +1),"")
In this case, the formula is in cell B50 and assumes the new date is in A50. It says given the date value in cell J + n, give me the value in cell J + n + 1.
I added a small validation check to see if there was a value in A50, but you may want to go deeper than that.
Also, if you want to make the value in B50 static, then just use the following code:
Sub mySub()
Dim x As Range 'I assume this range will be for your currentm, working worksheet
Set x = Range("B50", "B50")
x.Formula = "=IF(A50<>"""",INDEX(J:J,MATCH(A50,Codes!J:J,0) +1),"""")"
x = x.Value
End Sub