2013-07-17 97 views
0

我一直在努力解決這個問題幾個小時,並繼續打牆。我非常接近,但有小的細節錯誤。目前,我在excel vba中使用= weeknum來動態創建一行並接收#NUM!錯誤。它似乎工作時,我引用一個單元格,但當我手動輸入日期時,我得到類型不匹配的錯誤,並改變其他錯誤。我使用的日期格式是6/3/2013Excel財政周計算器

任何幫助非常感謝,並感謝您的時間!

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 

回答

0
fw_calc = Application.WeekNum(test, ReturnType) 

但您沒有給ReturnType一個值,因此它的默認值爲0,這不是一個可接受的值。如果省略,則默認爲每週開始的一天(星期日)。

+0

工作就像一個魅力,謝謝安迪! – Tyler

1

好的我看到你的問題了。嘗試使用以下行:

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

爲了解釋清楚,在WEEKNUM()功能想要一個Excel序列日期,所以我們需要先創建一個。這樣做的功能是DATE(),它需要單獨的年份,月份和日期(按此順序)。因此,我們使用VBA函數Day()Month()Year()解析出從你的約會細胞(test)的三個組成部分,然後將它們傳遞到DATE()功能,像這樣:

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

這將返回日期序列。然後我們將該序列作爲參數傳遞給WEEKNUM以獲取星期編號。看起來有點尷尬,但你明白了。