Question

I've been working on solving this for a few hours now and keep hitting a wall. I am very close but having small detail errors. Currently I am using =weeknum in excel vba to dynamically create a row and receiving a #NUM! error. It seems to work when I reference a cell but when I manual enter a date I get type mismatch errors and varies other errors. The date format i am using is 6/3/2013

Any help is greatly appreciated and thank you for your time!

Sub Macro2()
    Dim xDate As Double
    Dim ReturnType As Integer

    TotalRowCount = ThisWorkbook.Sheets("sap").UsedRange.Rows.count
    Set entryDateRange = ThisWorkbook.Sheets("sap").Range("G2:G" & TotalRowCount)
'my attempt at setting the datatype for the row, I dont think this is needed, but was one solution I saw
    'Range("M2:M" & TotalRowCount).NumberFormat = "@"
'create a collumn to hold the fiscal week output
    ThisWorkbook.Sheets("sap").Range("M1") = "FW"

    For Each test In entryDateRange
        CurrentRow = test.Row
        fw_calc = Application.Evaluate("=WEEKNUM(G" & CurrentRow & "," & ReturnType & ")")
        ' In place of (G" & CurrentRow.. etc I would prefer to use test if possible
        Worksheets("sap").Cells(CurrentRow, 13) = fw_calc
    Next test
End Sub
Was it helpful?

Solution 2

fw_calc = Application.WeekNum(test, ReturnType)

but you haven't given ReturnType a value so it has its default value of 0, which is not an acceptable value. If omitted it defaults to 1 (Sunday) the day the week begins.

OTHER TIPS

OK I see your problem. Try using the following line:

fw_calc = Application.Evaluate("=WEEKNUM(DATE(" & Year(test.value) & "," & Month(test.value) & ", " & Day(test.value) & "))")

To explain more clearly, the WEEKNUM() function wants an excel serial date, so we need to create one first. The function to do that with is DATE(), which requires a separate year, month and day (in that order). So we use the VBA functions Day(), Month() and Year() to parse out the three components from your date cell (test), then pass them in to the DATE() function like so:

"DATE(" & Year(test.value) & ", " & Month(test.value) & ", " & Day(test.value) & ")"

This returns the date serial. Then we pass that serial as the argument to WEEKNUM to get the week number. Looks a bit awkward, but you get the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top