excel - 在模块中使用自定义 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
此函数工作正常(如果在单元格中作为公式手动输入),但我想在模块中使用该函数,以便它将第一列中的值用于(新)列中的所有后续行正确的。
如何在模块中调用该函数?我认识到我需要某种循环来遍历所有行。
解决方案
我发现这对我有用,也可以循环。
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
推荐阅读
- react-native - 我们如何使用 react-native-gifted-chat 库实现群聊功能
- async-await - 未捕获的 SyntaxError:await 仅在异步函数和模块的顶层主体中有效
- java - Freemarker 不在邮件模板上显示图像
- selenium - 如何使用 Selenium 和 python 单击 devtools 控制台选项卡
- php - 多列的 ORDER BY 不能与 mysql 中的 Join 一起使用
- postgresql - 无法升级实例,因为一个或多个数据库包含声明为 WITH OIDS 的表,目标版本不支持该表
- python - nbdev_build_lib - 类型错误:__init__() 缺少 2 个必需的位置参数:“cfg_path”和“cfg_name”
- python - 在python的grep命令中输入一个字符串
- git - 如何解决与 git 命令行的冲突以保持目标(Visual Studio 2019)?
- c++ - 如何使用现有 C++ 代码构建 .a(通用静态库)