4

I am working with Excel 2010.

I wish to convert a given date from the format mm/dd/yyyy to the format Wyy"weeknumber"

For example, 4/10/2017 would become W1715, since it is week 15 of 2017.

The below shown image is of the excel table I am working on. I want to convert the dates in column LT Verification - Planned Date to the week number format mentioned above, in column LT Verification - Planned Week Numbers.

Edit: Because this is part of a larger VBA process, I need it to be in VBA, not a cell formula.

I have written the following code:

Public Sub WeekNumbers()

Dim lastRow As Integer
    lastRow = Range("A1:AZ1").Find("*", , , , xlByRows, xlPrevious).Row

Dim myRange As Range
    Set myRange = Range("A1:AZ1" & lastRow)

Dim myCell As Range
    For Each myCell In myRange

myCell.Offset(0, 1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)**

 Next myCell

 End Sub

This code gives me error at myCell.Offset(0, 1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)

Here I have a excel workbook which will be updated every week. So, each time it is updated, it runs a macro to import data from another file & perform the week number activity & create a pivot table.

So, the sheet name changes every week. Also, the column headers may be in different columns in different weeks. Also, the number of rows may also change every week.

So, I need to specify column & row range dynamically based on that weeks data. And have the week numbers in the column based on the column header rather than the column name (A or B or Z...)

Excel Table

Olivia
  • 177
  • 1
  • 2
  • 9
  • What have you tried? See here for some help: https://exceljet.net/formula/get-week-number-from-date See here for how to ask a question: http://stackoverflow.com/help/how-to-ask – OpiesDad Apr 11 '17 at 13:37
  • 1
    This is simple to do using formulae. Have you tried anything yet? Check out the MSDN pages [`ISOWEEK`](https://support.office.com/en-gb/article/ISOWEEKNUM-function-1c2d0afe-d25b-4ab1-8894-8d0520e90e0e), [`TEXT`](https://support.office.com/en-gb/article/TEXT-function-20d5ac4d-7b94-49fd-bb38-93d29371225c) and [`CONCATENATE`](https://support.office.com/en-gb/article/CONCATENATE-function-8f8ae884-2ca8-4f7a-b093-75d702bea31d) (hyperlinks). – G42 Apr 11 '17 at 13:40
  • You're starting to change the scope of your question. If you have code which successfully does your formatting, then accept the best answer below. To look for the column, you should use something like `rw = ActiveSheet.Rows(1).Find(what:="LT Verification - Planned Date", lookat:=xlwhole).Column`. If you need more help, ask a separate question specifically about that. – Wolfie Apr 11 '17 at 15:31
  • I guess you are right I need to ask a separate question about the range. But even though I put the range (specific for this week) the error in finding week number still exists. – Olivia Apr 11 '17 at 15:49
  • Did you try the fix in my answer (edit 2)? – Wolfie Apr 11 '17 at 15:58
  • @Wolfie: Thank you so much for the help. I used A.S.H's code & it works well for me! :) – Olivia Apr 11 '17 at 16:39

3 Answers3

3

This can be achieved easily with a cell formula:

="W" & RIGHT(YEAR(A1),2) & WEEKNUM(A1)

Where A1 can be replaced by the cell containing the date.

In VBA this is equivalent to

With Thisworkbook.Sheets("Sheet1")
    .Range("A2").Value = "W" & Right(Year(.Range("A1").Value), 2) & Application.WorksheetFunction.WeekNum(.Range("A1").Value)
End With

Edit:

To fill an entire range, you could loop over the cells, apply the VBA calculation as above.

Dim myRange as Range
Set myRange = Thisworkbook.Sheets("Sheet1").Range("A1:A10")

Dim myCell as Range
For Each myCell in myRange
    myCell.Offset(0,1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)
Next myCell

There are many methods for finding the last row in a range, so I'll leave that to you if you don't know your range.


Edit 2: in response to your error edit.

You have used the following line to define your range:

Set myRange = Range("A1:AZ1" & lastRow)

Let's imaging you have lastRow = 20, you now have

myRange.Address = "A1:AZ120"

Which is clearly wrong, you shouldn't have the 1 after the AZ. Also I don't know why you've gone to column AZ, if all of your date data is in column A, you should use

Set myRange = Range("A1:A" & lastRow)

The loop you've implemented uses an offset, so the values in column B are changed to reflect those in column A. You can't then set column C according to column B!

Community
  • 1
  • 1
Wolfie
  • 27,562
  • 7
  • 28
  • 55
  • 1
    This works great. But, I need to automate the entire process to fill the entire column and not just one cell. – Olivia Apr 11 '17 at 13:48
  • `Public Sub WeekNumbers() Dim lastRow As Integer lastRow = Range("A1:AZ1").Find("*", , , , xlByRows, xlPrevious).Row Dim myRange As Range Set myRange = Range("A1:AZ1" & lastRow) Dim myCell As Range For Each myCell In myRange myCell.Offset(0, 1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value) Next myCell End Sub` – Olivia Apr 11 '17 at 14:31
  • What do you expect me to do with that dump of code? – Wolfie Apr 11 '17 at 14:34
  • Sorry for the mess. I am trying to edit it and have a line break. But, I am not able to do so. Please bear with me till I figure that out! – Olivia Apr 11 '17 at 14:35
  • 1
    You cannot add line breaks to comments. If this extends your question then insert it as an edit (click edit below the question tags) – Wolfie Apr 11 '17 at 14:39
  • I have added another edit to answer your problem. For future reference, you should always include *which* error VBA is giving you, as this helps diagnose the problem! – Wolfie Apr 11 '17 at 14:57
  • @ Wolfie: I will try to explain better. Please see the edit in my question – Olivia Apr 11 '17 at 15:06
2

In VBA, you can get your string by using the Format function. "\Wyyww" is the format you are looking for, where \ is used to escape the interpretation of the first W character and to take it as a litteral.

myCell.Offset(0,1).Value = Format(myCell.Value, "\Wyyww")

More

You have to setup correctly the range for your loop. If your dates are in some column with header "LT Verificiation - Planned Date", you can try this:

Dim ws As Worksheet
Set ws = ActiveSheet ' <-- you can change this into something explicit like Sheets(someIndex)...

Dim myCell As Range
Set myCell = ws.Rows(1).Find("LT Verificiation - Planned Date")
For Each myCell In ws.Range(myCell.Offset(1), ws.Cells(ws.Rows.Count, myCell.Column).End(xlUp))
    If IsDate(myCell.value) Then myCell.Offset(, 1).value = Format(myCell.value, "\Wyyww")
Next myCell
A.S.H
  • 29,101
  • 5
  • 23
  • 50
  • Thanks! The code runs but nothing gets updated. And it does not show any error! – Olivia Apr 11 '17 at 15:22
  • @Pooja That's because your code to set the ranges is wrong. I though Wolfie was working on that. I'll edit to clarify. – A.S.H Apr 11 '17 at 15:24
  • @ A.S.H: Please see the edit my question. I have tried to better explain what I am actually looking for & I have also explained about the range problem. – Olivia Apr 11 '17 at 15:29
  • @Pooja ok, so what's the column's name that you want to look for, is it always `"LT Verficiation - Planned Date"`? and is it always in row 1? – A.S.H Apr 11 '17 at 15:38
  • This week I have columns from **A:AN**. The column header which is the input for weeknumber is **"LT Verification - Planned Date"** which is in column **AI** and the output column is **AJ** with column header **"LT - Verification - Planned Week Number"**.The column range **A:AN** can also change & columns **AI** and **AJ** can also chnage every week. – Olivia Apr 11 '17 at 15:46
  • Ok try the edited code. It only assumes that the *"Planned Week"* column always comes next to the input column, and that the header is row 1. If that's not the case we can tweak it further. – A.S.H Apr 11 '17 at 15:49
  • `For Each myCell In ws.Range(myCell.Offset(1), ws.Cells(ws.Rows.Count, myCell.Column).End(xlUp))` this line gives the error **Object variable or With block variable not set** – Olivia Apr 11 '17 at 15:54
  • @Pooja Means it did not find the *"LT Verificiation - Planned Date"* :(. You need to verify "my assumptions" with the layout of your worksheet. As it stands, the code runs perfectly in my tests, but again, with the assumptions I stated in a previous comment. – A.S.H Apr 11 '17 at 15:58
  • Sorry about the confusion. But here I get the week number as single digit for example, if the week number is 8, it give W178 but I am looking for W1708. – Olivia Apr 11 '17 at 16:12
  • @ A.S.H Also, I am looking for ISO Week number. This gives me wrong week numbers. – Olivia Apr 11 '17 at 16:17
  • ok, there are two problems here then. To get always two digits, the number of digits, change into this `myCell.Offset(, 1).value = Format(myCell.value, "\Wyy") & Format(WorksheetFunction.WeekNum(myCell.value), "00")`. to get ISO week number, this should be subject of another question (after some googling of course) :) – A.S.H Apr 11 '17 at 16:29
  • Thank you so much. Will try googling. – Olivia Apr 11 '17 at 16:33
  • 1
    Did not have to google and got the answer. Played around with the code. `myCell.Offset(, 1).Value = Format(myCell.Value, "\Wyy") & Format(ISOweeknum(myCell.Value), "00")`. Thank you for the help! :) – Olivia Apr 11 '17 at 16:37
  • @Pooja Wow, that's great. Wasn't aware of `ISOWEEKNUM`. See, you taught me something as well :). But I think you still need to prefix it with `WorksheetFunction.`, dont you? – A.S.H Apr 11 '17 at 16:41
  • Thank you for being humble! And, we do not need to prefix it with `WorksheetFunction`. I believe the reason is `ISOWEEKNUM` does not exist as a workshhet formula in Excel 2010. Do you think the reason is correct? – Olivia Apr 11 '17 at 16:58
  • @Pooja I am using Excel 2013 and I do have the `IsoWeekNum` in Excel. I cannot call it directly from VBA. Maybe your project has set some reference to some library that has it, I have no clue. But I am happy with it, I can use `WorksheetFunction` when needed. – A.S.H Apr 11 '17 at 17:05
0

I don't think you need VBA for this, try this formula:

=RIGHT(YEAR(A1),2)&WEEKNUM(A1)&"W"

Of course, if you insist on VBA, you can always turn Excel Formulas into VBA code. In this case:

Dim rngInput As Range
Dim rngOutput As Range
With Application.WorksheetFunction
    rngOutput.Value = .Right(.Year(rngInput.Value), 2) & .Weeknum(rngInput.Value) & "W"
End With

Or you may even set the Formula, and Insert the Value, like this

Dim rngInput As Range
Dim rngOutput As Range
rngOutput.Formula = "=RIGHT(YEAR(" & rngInput.Address(False, False) & "),2)&WEEKNUM(" & rngInput.Address(False, False) & ")&""W"""
rngOutput.Value = rngOutput.Value
z32a7ul
  • 3,695
  • 3
  • 21
  • 45
  • Thanks for the reply! But, this file has to run & import data from some other file & get updated automatically every week when someone runs it. So, I need to automate the process using VBA code. – Olivia Apr 11 '17 at 13:41
  • Setting the formula like that is not going to work, all of the cells would use `A1` as their input... – Wolfie Apr 11 '17 at 13:54