excel:使用find的vbatypes不匹配
我有这张表:
-
如果第一列的单元格中的值是“Nãomarcouférias”,那么它应该search整个
A
列A
并且发现该特定人员的唯一编号不止一次出现。 -
如果唯一编号出现两次或更多,并且该行的第一列不是“Nãomarcouférias”,那么它应该与当前年份进行比较,并在
K
列的相应单元格中写入ATUAL
。 如果这是真的,那么K
列中具有“Nãomarcouférias”的行应该是空白的。
这是我的工作表:
这就是我想要发生的事情:
正如你所看到的,因为我有两个条目号码59837
,其中之一是“Nãomarcouférias”,我希望它通过列A运行,并查找是否存在另一个条目,因为它是最新的,它应该写“ATUAL”on它。
这是我的代码:
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:types不匹配
这条线突出显示:
date1 = ws1.Cells(j, 9)
我的Excel是葡萄牙语,所以在这里我们使用date格式,如dd / mm / yyyy,我的所有列都设置为正确的date。
有没有人有build议? 我不知道为什么我再次遇到这种types的不匹配,因为我已经应用了这个解决scheme。
编辑:我已经testing了build议的解决scheme,但我仍然有同样的问题在同一行。
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
- 务必确保在代码顶部包含
Option Explicit
。 - 简单地写上
msgbox ws1.Cells(j, 9).address
在行上方的行中,并显示错误。 - 检查出现错误之前的MsgBox。
- 我可以打赌一个虚拟的啤酒,地址指向是一个值,这不是一个date。 例如
I6
在你的截图中,说一些关于假期和葡萄牙预订的好东西。
在你的代码中,你可以添加如If IsDate(ws1.cells(j,9)) then
。 它会检查给定的值是否是一个date。 在你的情况Não marcou férias
不能被parsing为Date
格式,因此你会得到一个错误。 或者只是尝试replace这样的代码位置:
For j = 2 To lastrow If ws1.Cells(j, 9) <> "Não marcou férias" Then date1 = ws1.Cells(j, 9) date2 = ws1.Cells(j, 12) k = ws1.Cells(j, 1).Value With ws1.Range("A2:A" & lastrow)
如果值不是“Nao marcou ferias”那么它可能是一个date(虽然,它更好地使用IsDate()
)。
玩得开心,TGIF