首页 > 解决方案 > 对源单元格本身应用 REPLACE 函数

问题描述

是否可以在 Excel 中格式化将公式的结果应用于单元格本身?

我有一个包含文本的单元格。文本以不需要的项目符号开头,我想使用下面的 REPLACE 功能删除前导项目符号。

将单元格 A2 视为包含带有前导特殊字符(项目符号)的文本的源,我想在其上应用此功能并希望将结果文本粘贴回 A2

=replace(A2,1,6,””)

有任何想法吗?

标签: excelvbaexcel-formula

解决方案


假设您在一列(示例代码中的 5)上的单元格包含“x 12345”、“x 3456”、“x abcd”等文本,将转换为:“12345”、“3456”、“abcd”等。您可以设置strRepl为任何字符串:

Sub testReplace()
  Dim sh As Worksheet, colNo As Long, arrCol As Variant
  Dim lastRow As Long, i As Long, strRepl
   Set sh = ActiveSheet ' put here your sheet
   colNo = 5 'Column E:E
   strRepl = "x " 'use here your string to be removed
   lastRow = sh.Cells(sh.Rows.count, colNo).End(xlUp).Row
   arrCol = sh.Range(Cells(1, colNo), Cells(lastRow, colNo)).Value
   For i = 1 To UBound(arrCol)
        arrCol(i, 1) = Replace(arrCol(i, 1), "x ", "")
   Next i
   sh.Range(Cells(1, colNo), Cells(lastRow, colNo)) = arrCol
End Sub

推荐阅读