1

警告:我是菜鸟。

我写了一个 Sub 来查找带有红色文本的单元格并更改它们。

@ThinkerIV 给了我一个很棒的功能,可以放入一个单元格并将公式拖到相邻的单元格中,但是由于要处理的工作表数量,这不起作用。所以我写了我的 Sub,调用他的函数(见下面的代码)。我给它传递了一个单元格的范围,所以在我看来它应该可以工作吗?

但是,它在函数调用 DateValue() 的行上不断抛出类型不匹配(运行时错误代码 13)!当我在编辑器中将鼠标悬停在传递的范围上时,传递的范围显示值 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

编辑我还不能发布我自己的答案,所以我添加了这个解决方案:

向 Format() 提供数据时,第一个格式化为红色的单元格的内容不是文本形式。我没有采取任何方法来确保我传递了正确的数据类型。因此,在将单元格传递给函数之前将其格式化为文本 (foundCell.NumberFormat = "@") 的行就是修复它的原因。

当我将代码复制/粘贴到问题中时,该解决方案实际上已经编写好了——我只是不知道它已经修复了它,因为另一个 Sub 上的另一个错误。(我是一个菜鸟,并且在处理多个潜艇中的多个错误时感到困惑)我以为我已经用那条新线路再次尝试过,但是没有,所以仍然认为它不起作用。

感谢所有帮助过的人。我现在觉得有点傻,发现它是这样的。希望你原谅我的菜鸟糊涂 - 编辑器中的一个巨大列表中有太多的 Subs 和 Functions,我感到“头晕”......至少我可以发布一个解决方案以防其他菜鸟需要它!

4

1 回答 1

0

好的,我认为这里有两件事。首先,DateValue 函数采用日期的字符串表示形式,例如“01/01/2013”​​,当您从一个范围中传递一个 excel 日期时,您传递的是一个数字,例如 41275。这会引发运行时错误 13 .

但是,如果您已经有一个日期,为什么还要转换它呢?您似乎希望将所有红色单元格转换为日期 + 工作表名称。为此,您必须有字符串,例如“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
于 2013-07-31T00:35:00.413 回答