函数中使用DateValue()types不匹配错误,如何排除故障?

警告:我是一个noob。

我写了一个Sub来find带有红色文字的单元格并改变它们。

@ThinkerIV给了我一个很好的function,把一个单元格放到相邻的单元格中,但是由于要处理的工作表数量太多,所以不能工作。 所以我写了我的Sub,调用他的函数(见下面的代码)。 我通过了一个单元格的范围,所以在我看来,它应该工作?

但是,它一直抛出types不匹配(运行时错误代码13)在函数调用DateValue()! 当我将其hover在编辑器中时,传递的范围显示值1(这是它引用的单元格中的数字),但是我不知道这是单元格的内容还是显示了其他值1。

所以,我真的不知道如何找出这到底是为什么。 是不是我通过的范围不是正确的? 请告诉我为什么这个代码不会工作!

我尝试将该行更改为下面的注释行(以及其他一些盲目的更改),但是具有相同的错误。

提前致谢!

Sub redTextToRealDates() Dim dateTemp As Date Dim redCell As Range Dim foundCell As Range Dim thisSheetsRange As Range Dim busyCell As Range Dim redTextCells As Range Set thisSheetsRange = ActiveSheet.usedRange 'Build a range containing all the cells in a sheet containing red text. ' well... all cells formatted to HAVE red text, anyway. ' Anyone want to tell me how to write this to skip empty cells? ' Because I don't need to grab empty cells into this range... For Each busyCell In thisSheetsRange If (busyCell.Font.ColorIndex()) = 3 Then If redTextCells Is Nothing Then Set redTextCells = busyCell Else: Set redTextCells = Union(redTextCells, busyCell) End If End If Next busyCell 'Change unknown format cells to date cells populated with concantenated 'string of original contents and the active sheet's name. For Each foundCell In redTextCells foundCell.NumberFormat = "@" foundCell = GetConcantDate(foundCell) Next foundCell redTextCells.NumberFormat = "dd/mm/yy" On Error Resume Next End Sub Function GetConcantDate(rng As Range) As Date 'Original code supplied by ThinkerIV on StackOverflow.com Dim dtTemp As Date dtTemp = DateValue(rng.Range("A1").Value & " " & rng.Parent.Name) 'dateTemp = DateValue(foundCell.Value & " " & ActiveSheet.Name) GetConcantDate = dtTemp End Function 

编辑我不能发布我自己的答案,所以我join这个解决scheme:

将数据提供给Format()时,格式化为红色的第一个单元格的内容不是文本forms。 我没有采取任何方式来确保我传递了正确的数据types。 所以,在将它传递给函数之前,将单元格格式化为文本(foundCell.NumberFormat =“@”)的行是固定的。

当我将代码复制/粘贴到问题中时,解决scheme实际上已经写好了 – 我只是不知道它已经修复了它,因为另一个Sub上有另一个错误。 (我是一个noob和混淆处理多个潜艇中的多个错误)我以为我已经尝试了与新的一行,但没有,所以仍然认为这是行不通的。

感谢所有的帮助。 现在我觉得有点傻了,就是这样发现的。 希望你原谅我的菜鸟flubber – 太多的子和函数在编辑器中的一个巨大的名单,我得到了“晕”…至less我可以发布一个解决scheme,以防其他noob需要它!

好的,我认为这里有两件事。 首先,DateValue函数采用date的string表示forms,例如“01/01/2013”​​,当您通过某个范围的exceldate时,您正在传递一个数字,如41275.这会导致运行时错误13 。

但是,如果你已经有一个约会,为什么要转换呢? 您似乎希望将所有红色单元格转换为date+表单名称。 要做到这一点,你必须有string,例如“01/01/2013 Sheet1”,所以你不能在这里使用DateValue。 相反,也许尝试这样的事情:

 Public Function GetConcatDate(rng As Range) As String Dim dtTemp As String dtTemp = Format(rng.Range("A1").Value, "dd/mm/yyyy") & " " & rng.Parent.Name GetConcatDate = dtTemp End Function