微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

循环第一行的日期并匹配其他工作表的第一行

如何解决循环第一行的日期并匹配其他工作表的第一行

我希望在 Sheet1 Row1 中找到带有 2021 的单元格值,然后如果在 Sheet2("Monthly2") Row1 中找不到该单元格值,则将该日期粘贴到下一个可用单元格中。出于某种原因,此代码当前在 Sheet1 中找到带有 2021 的最后一个单元格,并且仅将其粘贴到 Sheets("Monthly2") 单元格 A1 中。

Sub Monthly2()

Dim Monthly2 As Worksheet
Dim celldate As Range,MatchingDate As Range
Dim wb As Workbook
Dim rng1 As Range,rng2 As Range
Dim rng As Range
Dim cell As Range

Set wb = ActiveWorkbook
Set rng1 = wb.Sheets("Sheet1").Range("A1:AD1")
Set rng2 = wb.Sheets("Monthly2").Range("A1:AD1")


For Each celldate In rng1

    If celldate Like "*2021*" Then   
    
            For Each MatchingDate In rng2
                        
            If celldate = MatchingDate Then            
                                  
            ElseIf celldate <> MatchingDate Then                      
                       
            Sheets("Monthly2").Range("A1:AD1").Value = celldate
                        
            End If
           
            Next MatchingDate
    
        End If         
    
Next celldate

End Sub

解决方法

为什么不尝试将值与适用于 2021 年的最小双倍值进行比较

例如。日期:2021 年 1 月 1 日是 44197.00 作为双值

如果你比较你的单元格>= 44197 那么至少是 2021 年

您也可以将年末 44561.00 添加为双精度值

Const YearBegin = 44197,YearEnds = 44561

Sub IterareDates()
    For Each CellDate In ActiveWorkbook.Sheets("Sheet1").Range("A1:AD1")
        'this if,indicate that value appertain to 2021
        If CellDate.Value >= YearBegin And CellDate.Value <= YearEnds Then
            'I dont understand those lines,I suppose you are trying to compare cell
            'by cell in 2 sheets,if im right,you are comparing 2 entire ranges,'you should compare each cell separately or sum values and if diferent set         which you need

            If ThisWorkbook.Application.WorksheetFunction.CountIf(Range("A1:AD1"),CellDate.Value) > 0 Then
                'exist
            Else
                'dont
            End If


        End If
    Next CellDate
End Sub
,

未经测试

Dim wb as Workbook
Dim rng1 as Range,rng2 as Range
Dim rng as Range,celldate as Range

Set wb = ActiveWorkbook
Set rng1 = wb.Sheets("Sheet1").Range("A1:AD1")
Set rng2 = wb.Sheets("Monthly").Range("A1:AD1")

For Each celldate In rng1
    If celldate Like "*2021*" Then
        Set rng = rng2.Find(celldate)
        If rng is Nothing Then
           ' not found
        Else
           ' found do something
        Endif
    End If
Next

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。