首页 > 解决方案 > 在模块中使用自定义 Excel 函数

问题描述

我在两列中有一些数据(列的长度将是动态的)。第一列的格式为:2021 年 9 月 1 日的总和 - 第二列只是数字(链接图片中的示例数据)。

我想清理第一列并将其放入另一列中的日期格式。我创建了一个自定义函数来从第一列中提取文本:

Function ReturnCellToLeft()

    ReturnCellToLeft = Application.Caller.Cells.Offset(0, -4).Value

    'ReturnCellToLeft = Application.Caller.Cells.Offset(0, -4).Value where -4 in this case 'is the number of columns to the left where the original data is stored.

    'The formula would be =RIGHT(ReturnCellToLeft(),LEN(ReturnCellToLeft())-7) as an example to extract the text 'to the right of the "Sum of " that begins the cell.
    ' 7 is the number of characters in "Sum of "

End Function

此函数工作正常(如果在单元格中作为公式手动输入),但我想在模块中使用该函数,以便它将第一列中的值用于(新)列中的所有后续行正确的。

如何在模块中调用该函数?我认识到我需要某种循环来遍历所有行。

样本数据

标签: excelvbafunction

解决方案


我发现这对我有用,也可以循环。

Sub LoopColumn()
'
' use a dynamic range to loop through data and extract the 10 rightmost 'characters which are dates in a text string

    Dim rngMyRange As Range

Range(Selection, Selection.End(xlDown)).Select

Set rngMyRange = Selection
    Dim c       As Range
   
'
    Range(ActiveCell, ActiveCell.End(xlDown)).Select

'
    For Each c In rngMyRange
        c = Mid(c, 8, 10)
    Next c
' formats range as short date
    rngMyRange.NumberFormat = "mm/dd/yyyy"
End Sub

推荐阅读