简体   繁体   English

VBA将日期更改为每月的第一天

[英]VBA changing the date to first day of month

Each week we receive a row of new data which is added to the top of the list of data (row 5). 每周我们都会收到一行新数据,这些数据将添加到数据列表的顶部(第5行)。 We only keep the most recent row of data from each month and delete the row below unless it's the next month example of spreadsheet (In the image I need to delete the row from April underneath). 除非是下个月的电子表格示例,否则我们仅保留每个月的最新数据行并删除下面的行(在图像中,我需要从下方的4月中删除该行)。 The problem is the way the date is formatted as it's dd/mm/yyyy which means if the day doesn't match the previous row, then it won't delete, even if the month is the same. 问题在于日期的格式设置为dd / mm / yyyy,这意味着如果日期与上一行不匹配,则即使月份相同,日期也不会删除。

So far I've got the code to insert a new row in row 5, I've attempted to change the date to the 1st of the month (with an 'invalid procedure or call' error), and I've got an IF statement for if the dates match then it'll delete row 6. 到目前为止,我已经有了在第5行中插入新行的代码,我试图将日期更改为每月的1号(出现“无效的过程或调用”错误),并且我有一个IF日期匹配的语句,它将删除第6行。

Worksheets("Weekly Ageing Summary").Rows("5:5").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

Worksheets("Weekly Ageing Summary").range("B5").Value = DateSerial(Year(Cells("B5")), Month(Cells("B5")), 1)

If Worksheets("Weekly Ageing Summary").range("B5").Value = Worksheets("Weekly Ageing Summary").range("B6").Value Then
    Rows(6).EntireRow.Delete
End If

This probably isn't the best logic to write the code but I'm just new to VBA and am unsure how else to do this. 这可能不是编写代码的最佳逻辑,但是我对VBA还是陌生的,不确定是否还有其他方法。

Thanks in advance :) 提前致谢 :)

I tried your example code and was getting the same error as you - I think the problem is the way you are doing your cell references (Cells("B5") instead of Cells(5, 2)). 我尝试了您的示例代码,并且遇到了与您相同的错误-我认为问题在于您对单元格进行引用的方式(Cells(“ B5”)而不是Cells(5,2))。

Try this: 尝试这个:

Worksheets("Weekly Ageing Summary").Range("B5").Value = DateSerial(Year(Cells(5, 2).Value), Month(Cells(5, 2).Value), 1)

If Worksheets("Weekly Ageing Summary").Range("B5").Value = Worksheets("Weekly Ageing Summary").Range("B6").Value Then
    Rows(6).EntireRow.Delete
End If

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM