【发布时间】:2017-07-07 14:47:32
【问题描述】:
我有这张表,其中:
如果
I列中单元格中的值是“Não marcou férias”,那么它应该搜索整个列A并查找该特定人员的唯一编号出现多次的所有时间。如果唯一编号出现两次或更多次,并且该行的列
I不是“Não marcou férias”,则应与当前年份进行比较,并在 @987654330 列的相应单元格中写入ATUAL@。如果是真的,那么K列中具有“Não marcou férias”的行应该是空白的。
这是我的工作表:
这就是我想要发生的事情:
如您所见,我有两个编号为 59837 的条目,其中一个是“Não marcou férias”,我希望它遍历 A 列并查找是否存在另一个条目,因为它是最新的,它应该在上面写上“ATUAL”。
这是我的代码:
Sub test()
Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim date1 As Date, date2 As Date
Set ws1 = Sheets("Plan1")
lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row
For j = 2 To lastrow
date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)
If ws1.Cells(j, 9) = "Não marcou férias" Then
k = ws1.Cells(j, 1).Value
With ws1.Range("A2:A" & lastrow)
Set c = .Find(k, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
If ws1.Cells(j, 9) <> "Não marcou férias" Then
If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then
ws1.Cells(j, 13) = "ATUAL"
Else
ws1.Cells(j, 13) = ""
End If
End If
Set c = .FindNext(c)
If c Is Nothing Then
GoTo DoneFinding
End If
Loop While c.Address <> firstAddress
End If
DoneFinding:
End With
End If
Next j
End Sub
但是当我尝试运行时,我得到:
运行时错误 13:类型不匹配
并且这一行被高亮显示:
date1 = ws1.Cells(j, 9)
我的 Excel 是葡萄牙语,所以在这里我们使用 dd/mm/yyyy 之类的日期格式,并且我的所有列都正确设置为日期。
有人有建议吗?我不知道为什么我已经应用了THIS 解决方案,所以我再次遇到这种类型不匹配。
编辑:我已经测试了建议的解决方案,但我仍然在同一行中遇到同样的问题。
Option Explicit
Sub test2()
Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim date1 As Date, date2 As Date
Dim k As Long
Dim c As Range
Dim firstAddress As String
Set ws1 = Sheets("Plan1")
lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row
For j = 2 To lastrow
date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)
If Not IsDate(ws1.Cells(j, 9)) Then
k = ws1.Cells(j, 1).Value
With ws1.Range("A2:A" & lastrow)
Set c = .Find(k, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
If IsDate(ws1.Cells(j, 9)) Then
If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then
ws1.Cells(j, 13) = "ATUAL"
Else
ws1.Cells(j, 13) = ""
End If
End If
Set c = .FindNext(c)
If c Is Nothing Then
GoTo DoneFinding
End If
Loop While c.Address <> firstAddress
End If
DoneFinding:
End With
End If
Next j
End Sub
【问题讨论】:
-
If ws1.Cells(j, 9) = "Não marcou férias" Then:ws1.Cells(j, 9)不是日期,所以date1 = ws1.Cells(j, 9)当然是type mismatch因为Dim date1 As Date:) 。我认为您应该首先与If IsDate(ws1.Cells(j, 9) )核对并考虑到这一点。 -
@A.S.H 我真的明白了,尽管我需要在该列中进行比较。例如,我尝试了 Vityata 的解决方案,Message Box 将 I6 指定为日期。我可以尝试改变我的比较。