简体   繁体   English

检查日期是否介于两个日期之间并返回一个字符串到另一列 Excel VBA

[英]Checking if a date falls between two dates and returns a string to another column in Excel VBA

I need to create a spreadsheet that will take a project date in Column C and then assign it a specific Period (Column B) based on what dates the project falls on.我需要创建一个电子表格,该电子表格将在 C 列中获取项目日期,然后根据项目所在的日期为其分配特定的期间(B 列)。

Ex.前任。 Period 1x1 (B2) is >= Period Start Date (A2) and < Period Start Date (A3).期间 1x1 (B2) >= 期间开始日期 (A2) 且 < 期间开始日期 (A3)。 Any Project Date (Column C) to fall in between those dates would be assigned as 1x1 in column N.介于这些日期之间的任何项目日期(C 列)将在 N 列中指定为 1x1。

Spreadsheet电子表格

Sub Main()


    Dim ProjectDate As Date
    Dim PeriodDate As Date
    Dim Period As String
    

    ProjectDate = Range("C2")
   

    
    If ProjectDate >= Range("A2") And ProjectDate < Range("A3") Then
    Period = "1x1"
    ElseIf ProjectDate >= Range("A3") And ProjectDate < Range("A4") Then
    Period = "1x2"
    End If
    
    Range("D2") = Period
    
    End Sub
    
    
    

This is as far as I have gotten (only 2 periods, I'll add the rest once I figure out what the issue is) but when I run it, it does not fill anything in Column D. I think this is because the If statement isn't considering the Range as Dates and therefore can't distinguish if the ProjectDate falls between that range.这是我得到的(只有 2 个周期,一旦我弄清楚问题是什么,我将添加 rest)但是当我运行它时,它不会在 D 列中填充任何内容。我认为这是因为 If语句没有将范围视为日期,因此无法区分 ProjectDate 是否落在该范围内。 I am also unsure how to expand it to further rows for the output Period as currently it's only going to display it in D2我也不确定如何将它扩展到 output Period 的更多行,因为目前它只会在 D2 中显示

EDIT: Removed the format code but it still does not return any values for column D编辑:删除了格式代码,但它仍然不返回 D 列的任何值

ProjectDate = Format(Date, "mm/dd/yy")

I just did a For Each Cell loop and was able to get it working我刚刚做了一个 For Each Cell 循环并且能够让它工作

    Sub Main()

    
For Each Cell In Range("C2:C1000")
    If Cell.Value >= Range("A2") And Cell.Value < Range("A3") Then
    Cell.Offset(0, 1).Value = Range("B2")
    ElseIf Cell.Value >= Range("A3") And Cell.Value < Range("A4") Then
    Cell.Offset(0, 1).Value = Range("B3")
     ElseIf Cell.Value >= Range("A4") And Cell.Value < Range("A5") Then
    Cell.Offset(0, 1).Value = Range("B4")

    End If
    Next Cell
    
    
    End Sub

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

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