简体   繁体   English

excel:比较日期的vba类型不匹配

[英]excel: vba type mismatch comparing dates

I'm trying to make a comparison between years from two dates (in different columns) and the current year date. 我试图比较两个日期(在不同的列中)和当前年份日期之间的年份。 If the year is the same then it should write on the corresponding row at column 13 the word "ATUAL", if the year is different then it should write nothing. 如果年份相同,则应在第13栏的相应行上写下“ATUAL”字样,如果年份不同则应该不写入任何内容。

This is what I've tried so far. 这是我到目前为止所尝试的。

Sub CopyColumn2()

Dim i As Long
Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim wbk As Workbook
Dim wb As Worksheet

Set wbk = Workbooks.Open("I:\CGP\DEOPEX\01 - Supervisão\01 - Administrativo\06- ADM - Taís e Natalia\Férias - Aprovadas\FÉRIAS TÉCNICOS EXTERNAS.xlsx")
Set ws1 = ThisWorkbook.Sheets("BASE_TOTAL")
Set ws2 = wbk.Worksheets("FUNCIONÁRIOS")

lastrow = ws2.Range("A" & Rows.Count).End(xlUp).Row


For j = 2 To lastrow
    If Year(ws1.Cells(j, 9)) = Year(Date) Or Year(ws1.Cells(j, 12)) = Year(Date) Then
        ws1.Cells(j, 13) = "ATUAL"
    Else
        ws1.Cells(j, 13) = ""
    End If
Next j   

End Sub

The dates are placed in columns I and L and all column is set as Date. 日期放在第I列和第L列中,所有列都设置为日期。 My Excel is in portuguese so my date format is dd/mm/yyyy. 我的Excel是葡萄牙语,所以我的日期格式是dd / mm / yyyy。

When I run my code, I receive this message: 当我运行我的代码时,我收到此消息:

Run-time error 13: Type mismatch 运行时错误13:类型不匹配

And this part is highlighted: 这一部分突出显示:

If Year(ws1.Cells(j, 9)) = Year(Date) Or Year(ws1.Cells(j, 12)) = Year(Date) Then

Is anyone knows what is the problem here? 有人知道这里有什么问题吗? It should work since all my dates are formatted the same way. 它应该工作,因为我的所有日​​期都以相同的方式格式化。

Try this: 尝试这个:

  1. Declare date variables Dim date1 As Date, date2 As Date 声明日期变量Dim date1 As Date, date2 As Date
  2. Set value for variable 设置变量的值

    date1 = ws1.Cells(j, 9) date2 = ws1.Cells(j, 12)

  3. Use variable in your If statement If语句中使用变量

    If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then

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

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