VBA代码从给定date获取周数
我正在使用Excel 2010。
我希望将格式为mm/dd/yyyy
的给定date转换为Wyy"weeknumber"
格式
例如,2017年4月10日将成为W1715
,因为它是2017年的第15周。
下面显示的图片是我正在处理的Excel表格。 我想将列LT Verification - Planned Date
中的LT Verification - Planned Date
转换为上面提到的星期编号格式,在LT Verification - Planned Week Numbers
。
编辑:因为这是一个更大的VBA过程的一部分,我需要它在VBA,而不是一个单元格公式。
我写了下面的代码:
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
这段代码在myCell.Offset(0, 1).Value = "W" & Right(Year(myCell.Value), 2) & Application.WorksheetFunction.WeekNum(myCell.Value)
在这里,我有一个每周更新的Excel工作簿。 因此,每次更新时,它都会运行一个macros来导入另一个文件中的数据并执行周数活动并创build数据透视表。
所以,表格名称每周都在变化。 此外,列标题可能在不同的星期在不同的列。 而且,行数也可能每周都在变化。
所以,我需要根据星期数据dynamic地指定列和行的范围。 并根据列标题而不是列名(A或B或Z …)
在VBA
,您可以使用Format
function获取string。 "\Wyyww"
是您要查找的格式,其中\
用于避开第一个W
字符的解释,并将其作为一个string。
myCell.Offset(0,1).Value = Format(myCell.Value, "\Wyyww")
更多
你必须正确地设置你的循环范围。 如果您的date位于标题为"LT Verificiation - Planned Date"
,则可以尝试以下操作:
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
这可以通过单元格公式轻松实现:
="W" & RIGHT(YEAR(A1),2) & WEEKNUM(A1)
A1
可以被包含date的单元replace。
在VBA中这相当于
With Thisworkbook.Sheets("Sheet1") .Range("A2").Value = "W" & Right(Year(.Range("A1").Value), 2) & Application.WorksheetFunction.WeekNum(.Range("A1").Value) End With
编辑 :
要填充整个范围,可以循环遍历单元格,应用上面的VBA计算。
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
有很多方法可以find范围内的最后一行 ,所以如果你不知道范围 ,我会把它留给你。
编辑2 :回应你的错误编辑。
您已使用以下行来定义您的范围:
Set myRange = Range("A1:AZ1" & lastRow)
让我们想象你有lastRow = 20
,你现在有
myRange.Address = "A1:AZ120"
这显然是错误的,你不应该在AZ
之后有1
。 此外,我不知道你为什么去AZ
列,如果所有的date数据是在列A
,你应该使用
Set myRange = Range("A1:A" & lastRow)
你已经实现的循环使用了一个偏移量,所以B
列中的值被改变,以反映列A中的值。然后你不能根据B
列设置C
列!
我不认为你需要这个VBA,试试这个公式:
=RIGHT(YEAR(A1),2)&WEEKNUM(A1)&"W"
当然,如果你坚持VBA,你总是可以把Excel公式转换成VBA代码。 在这种情况下:
Dim rngInput As Range Dim rngOutput As Range With Application.WorksheetFunction rngOutput.Value = .Right(.Year(rngInput.Value), 2) & .Weeknum(rngInput.Value) & "W" End With
或者你甚至可以设置公式,并插入值,像这样
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