macro to extract dates from a weeks date range string and add 7 days to print next date range - date

I am writing a macro that processes an excel with lots of data. One of the rows contains a date range like wkstartdate - wkenddate and I would like to use dateadd function to print next date range every week (like '27-01-14 - 02-02-14' in below case) but unable to do so.
'06-01-14 - 12-01-14'
'13-01-14 - 19-01-14'
'20-01-14 - 26-01-14'
I used below excerpt which fails:
Range("E" & Lastrow).Select
prwk = Split(ActiveCell.Value, "-")
'curr_wkstart = DateAdd("d", 7, prwk(1)) 'error as maybe prwk(1) isnt correct format
'curr_wkend = DateAdd("d", 7, prwk(2)) 'error
Range("E" & Lastrow + 1).Value = curr_wkstart & curr_wkend 'no result
For testing purpose I print, prwk(1) which is 20/01/14 in the above case, in a diff cell and add 7 days, which gives me 1/21/2020 instead of '27/01/14'. I also tried using Cdate function, but still error
Can you please advise??

I think what you want to use here are the Format and DateSerial functions. Here's how I came at it:
Function GetNextWeek(TheStartWeek)
a = Split(TheStartWeek, " - ")
b = Split(a(1), "-")
c = DateSerial(b(2), b(1), b(0)) + 1
d = c + 6
GetNextWeek = Format(c, "dd-mm-yy") & " - " & Format(d, "dd-mm-yy")
End Function
Sub Test()
Debug.Print GetNextWeek("13-01-14 - 19-01-14") 'Givs you "20-01-14 - 26-01-14"
End Sub
Hope this helps.

Related

VB6 Alternate 7 images every calendar week continuously

I am (still) programming in VB6, but I think this problem is not program language related.
I need to show one Picture out of 7 Pictures (named 1.jpg to 7.jpg) every calendar week, beginning with Calendar week 3, which shows picture nr.1
Example:
(year and calendar week together as 2022/03)
202203=1.jpg
202204=2.jpg
202205=3.jpg
202206=4.jpg
202207=5.jpg
202208=6.jpg
202209=7.jpg
202210=1.jpg
202211=2.jpg
etc.
How can I do this??
Also, Years can have 52 or 53 weeks, but this has to continue like above...
Appreciate any help, thank you in advance.
Here is some code that gives the results you desire. It should be fairly self-explanatory:
Option Explicit
Private Sub Test()
Dim dt As Date
Dim i As Integer
dt = DateSerial(2022, 1, 17) 'start at 3rd calendar week
For i = 1 To 100
Debug.Print Format(dt, "mm/dd/yyyy") & vbTab & Year(dt) & _
Format(ISOWeekNumber(dt), "00") & vbTab & GetPicture(dt)
dt = DateAdd("d", 1, dt)
Next
End Sub
Private Function GetPicture(ByVal dt As Date) As String
Dim dp As Integer
dp = ISOWeekNumber(dt) Mod 7 - 2
If dp <= 0 Then dp = dp + 7
GetPicture = dp & ".jpg"
End Function
Private Function ISOWeekNumber(ByVal dt As Date) As Integer
ISOWeekNumber = DatePart("ww", dt, vbMonday, vbFirstFourDays)
End Function
This produces the following results:

Search a row a dates, identify a start date and end date, merge cells in row from start date to end date

I have searched high and low for examples to guide me in the development of a calendar spreadsheet. The customer has very specific guidelines.
First 11 columns contain event details are setup as filters
Row 1 is currently blank, but will be used for heading
Row 2 from column K to infinity (BXY) is the year
Row 3 from column K to BXY is the month
Row 4 from column K to BXY is the day
Other notes:
Cell K6 has the Date 1-Jul-18.
All cells in row 4 continue as =K$6+1..etc.
The week is calculated with the formula:
=CONCATENATE("WEEK ", IF((IF(MONTH(K6)>=10, WEEKNUM(K6)-WEEKNUM(DATE(YEAR(K6),10,1))+1, 53-WEEKNUM(DATE(YEAR(K6)-1,10,1))+WEEKNUM(K6)))=53,1,(IF(MONTH(K6)>=10, WEEKNUM(K6)-WEEKNUM(DATE(YEAR(K6),10,1))+1,53-WEEKNUM(DATE(YEAR(K6)-1,10,1))+WEEKNUM(K6)))))
All cells in row 2 are calculated:
=YEAR($K$6)
Now to my dilemma. I am working on a userform for the user to input all data that populates the next empty row in the spreadsheet. I can not post the code that does that, as it is on a proprietary computer system. But, that code that populates the filter range A through J works fine. This code finds the next empty row:
lastRow = ws.Cells.Find(What:="*", LookIn=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
As part of the form the user inputs the start date and end date of an event. I am trying to search row 4 for the start date and end date, merge all cells between the start date and end date and insert the event title into the merged cell.
This is my code so far for searching Row 4:
For Each eventDate In .Range("K$4:BXY$4)
If IsDate(eventDate.Value) = IsDate(Me.tbStartDate.Value) Then
.Cells(lastRow, eventDate.Address(RowAbsolute:=True, ColumnAbsolute:=False)).Value = Me.tbEventName.Value
End If
Next eventDate
I am new to excel programming, and really only a hobbyist programmer. I was given this task at work and have been reading and researching examples for what I am trying to do...to no avail.
I am looking at modifying this snippet to work:
For iCounter = myLastRow To myFirstRow Step -1
If .Cells(iCounter, myCriteriaColumn).Value = myCriteria Then
.Range(.Cells(iCounter, myFirstColumn), .Cells(iCounter, myLastColumn)).Merge
Next iCounter
with this:
LastCol = sh.Cells.Find(What:="*", After:=sh.Range("A1"), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
Any assistance and guidance on how to accomplish this will be much appreciated.
v/r
Dusty
I figured it out, probably not the best solution, but it works:
lastRow = .Cells.Find(What:="*",_
LookIn:=xlFormulas,_
LookAt:=xlPart,_
SearchOrder:=xlByRows,_
SearchDirection:=xlPrevious).Row + 1
eventName = Me.tbID.Value + " " +_
Me.tbOpName + " " +_
Me.tbStartDate.Value + "-" +_
Me.tbEndDate.Value
startDate = Format(Me.tbStartDate.Value, "dd-mmm-yyyy;#")
endDate = Format(Me.tbEndDate.Value, "dd-mmm-yyyy;#")
For startCol = 14 to 959
startDateColumn = Format(.Cells(6, startCol).Value, "dd-mmm-yyyy;#")
If StrComp(startDate, startDateColumn, vbTextCompare) = 0 Then
For endCol = 14 to 959
endDateColumn = Format(.Cells(6, endCol).Value, "dd-mmm-yyyy;#")
If StrComp(endDate, endDateColumn, vbTextCompare) = 0 Then
.Range(.Cells(lastRow, startCol), .Cells(lastRow, endCol)).Merge
.Cells(lastRow, startCol).Value = eventName
Exit For
End If
Next endCol
End If
Next startCol

VBA Excel make array of sequential numbers

I am working in VBA for Excel at the moment but am really only versed in Matlab. It's important for my work to stay in the memory of vba (not on the worksheets of excel) for time purposes.
What I need to do is make an array of sequential integers, say 4000 through 5000.
In matlab this is really easy, I would just do... i = 4000:5000, or i=4000:1:5000. With the 1 in the second case being my 'step.'
I was wondering what is the best way to achieve this result in vba?
Thanks
Without looping - Just seen Rory's same answer above after posting
Sub MakeArray()
Dim x As Long, y As Long, arr As Variant
x = 4000: y = 5000
arr = Evaluate("Row(" & x & ":" & y & ")")
'Show result
Sheets(1).Range("A1").Resize(y - x + 1) = arr
End Sub
The following is an example of creating and then displaying a set of sequential numbers:
Sub seqnum()
Dim firstnum As Long, secnum As Long
firstnum = 7
secnum = 23
ReDim ary(1 To secnum - firstnum + 1) As Long
For i = 1 To UBound(ary)
ary(i) = firstnum + (i - 1)
Next i
msg = ""
For i = 1 To UBound(ary)
msg = msg & i & vbTab & ary(i) & vbCrLf
Next i
MsgBox msg
End Sub
I Us "Fill" - "Series":
Write in first cell number ex. 400 and in the "Series" window insert increment step and in "Stop Value" last value. ex. 420
Or with Macro
Range("I1").Select
ActiveCell.FormulaR1C1 = "4000"
Range("I1").Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
Step:=1, Stop:=4020, Trend:=False

Data control from textbox and inverted day/month values

I need to check if the date entered in a textbox is valid. It has to be a single textbox, so no workaround this way.
Now, I have this code:
Private Sub cmdOK_Click()
Dim dataAnalisi As Date
If IsDate(txtDataAnalisi.Value) Then
dataAnalisi = txtDataAnalisi.Value
Dim giornoAnalisi, meseAnalisi As Integer
giornoAnalisi = Format(dataAnalisi, "dd")
meseAnalisi = Format(dataAnalisi, "mm")
If giornoAnalisi <= 31 And meseAnalisi <= 12 Then
Call arrayList(dataAnalisi)
Unload Me
Else
GoTo DateError
End If
Else
DateError:
MsgBox "Inserire una data formattata correttamente!", vbCritical, "Errore nell'inserimento!"
txtDataAnalisi.SetFocus
End If
End Sub
Sorry if it has text in Italian. The function works decently, the only problem is that if I input for instance 11/14/12 (where the date is dd/mm/yy and 14 was a mistype) it inverts the day and month values. Instead, I want the sub to tell the user to check his input again! Can you help me? Thank you!
There are variations of this question every month or so. I am convinced that Excel will treat a date that is a valid American date as an American date. I have thought this for many years but others disagree.
I use functions like the one below which check for formats I believe Excel will misinterpret and convert them to an unambiguous format.
I use the English abbreviations for months. I believe French is the only language that does not permit three character abbreviations for months so perhaps you have your own set. You will have to adapt that part of the routine to your requirement.
Hopes this helps.
Function MyDateValue(ByVal DateIn As String, ByRef DateOut As Date) As Boolean
' DateIn is a value to be checked as a valid date.
' If it is a valid date, DateOut is set to its value and the function
' returns True.
' Excel misinterprets dates such as "4/14/11" as 14 April 2011. This routine
' checks for such dates and, if necessary, changes them to an unambiguous
' format before calling IsDate and DateValue.
Dim DatePart() As String
Dim MonthNum As Long
Const MonthAbbr As String = "janfebmaraprmayjunjulaugsepoctnovdec"
' Replace popular delimiters with Microsoft standard
DateIn = Replace(DateIn, "-", "/")
DateIn = Replace(DateIn, "\", "/")
DatePart = Split(DateIn, "/")
If UBound(DatePart) = 2 Then
' DateStg is three values separated by delimiters
' Check middle part
If IsNumeric(DatePart(1)) Then
MonthNum = Val(DatePart(1))
If MonthNum >= 1 And MonthNum <= 12 Then
' Middle part could be numeric month
' Convert to format Excel does not misinterpret
'Debug.Assert False
DatePart(1) = Mid(MonthAbbr, ((MonthNum - 1) * 3) + 1, 3)
DateIn = Join(DatePart, "-")
If IsDate(DateIn) Then
DateOut = DateValue(DateIn)
MyDateValue = True
Exit Function
End If
Else
' Middle part cannot be a month
'Debug.Assert False
MyDateValue = False
Exit Function
End If
Else
'Debug.Assert False
' The middle part is not a number. It could be a month abbreviation
MonthNum = InStr(1, MonthAbbr, LCase(DatePart(1)))
If MonthNum = 0 Then
' The middle portion is neither a month number nor a month abbreviation
Debug.Assert False
MyDateValue = False
Else
' The middle portion is a month abbreviation.
' Excel will handle date correctly
'Debug.Assert False
MonthNum = (MonthNum - 1) / 3 + 1
DateIn = Join(DatePart, "-")
If IsDate(DateIn) Then
'Debug.Assert False
DateOut = DateValue(DateIn)
MyDateValue = True
Exit Function
End If
End If
End If
Else
' Debug.Assert False
' Use IsDate for other formats
If IsDate(DateIn) Then
' Debug.Assert False
DateOut = DateValue(DateIn)
MyDateValue = True
Exit Function
Else
' Debug.Assert False
MyDateValue = False
End If
End If
End Function

VBScript How can I Format Date?

I want the date to look like MM-DD-YYYY instead of MM/DD/YYYY.
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.
Function myDateFormat(myDate)
d = TwoDigits(Day(myDate))
m = TwoDigits(Month(myDate))
y = Year(myDate)
myDateFormat= m & "-" & d & "-" & y
End Function
Function TwoDigits(num)
If(Len(num)=1) Then
TwoDigits="0"&num
Else
TwoDigits=num
End If
End Function
edit: added function to format day and month as 0n if value is less than 10.
Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.
Thus:
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.
If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use
Replace(FormatDateTime(d,2),"/","-")
'for unique file names I use
Dim ts, logfile, thisScript
thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension
ts = timeStamp
logfile = thisScript & "_" & ts
' ======
Function timeStamp()
timeStamp = Year(Now) & "-" & _
Right("0" & Month(Now),2) & "-" & _
Right("0" & Day(Now),2) & "_" & _
Right("0" & Hour(Now),2) & _
Right("0" & Minute(Now),2) ' '& _ Right("0" & Second(Now),2)
End Function
' ======
This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").
option explicit
Wscript.Echo "Today is " & myDate(now)
' date formatted as your request
Function myDate(dt)
dim d,m,y, sep
sep = "-"
' right(..) here works as rpad(x,2,"0")
d = right("0" & datePart("d",dt),2)
m = right("0" & datePart("m",dt),2)
y = datePart("yyyy",dt)
myDate= m & sep & d & sep & y
End Function
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019 (depending on the current date)