【问题标题】:Excel - Find and replace using a combined (value and formatting) conditionExcel - 使用组合(值和格式)条件查找和替换
【发布时间】:2017-02-05 05:35:14
【问题描述】:

我想为工作表中的所有单元格清空单元格格式并将其设置为常规:

  • 包含“MyText”和
  • 格式为百分比

我正在使用查找和替换对话框 (CTRL+H),但是:

  • 如果我将“替换为”框留空,则只替换格式; “MyText”仍然存在;
  • 如果我在“替换为”框中写入“SomeText”,也会执行文本替换,以及格式替换

看来我无法一次性获得两个替换项(空文本和更改的格式)。

是否有可以在“替换为:”字段中使用的“无”通配符?或者任何其他简单的解决方案?

更新: 我尝试录制宏。 这会进行文本格式替换:

Application.FindFormat.NumberFormat = "0.00%"
Application.ReplaceFormat.NumberFormat = "General"
Cells.Replace What:="MyText", Replacement:="nothing", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=True, _
    ReplaceFormat:=True

但是如果我删除替换文本,它只会进行格式替换(这在某种程度上是有意义的,但这不是我想要实现的)

Application.FindFormat.NumberFormat = "0.00%"
Application.ReplaceFormat.NumberFormat = "General"
Cells.Replace What:="MyText", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=True, _
    ReplaceFormat:=True

【问题讨论】:

  • 单元格是否包含 textformulas 返回文本??
  • @Gary'sStudent :没有公式,只有文本;如果它有公式,则文本替换根本不起作用;但如果我提供这个论点,它就会起作用;我只需要知道如何提供blank 参数; "" 不工作...

标签: excel replace format find


【解决方案1】:

也许一个简单的循环可能更容易:

Sub FixingData()
    Dim r As Range

    For Each r In ActiveSheet.Cells.SpecialCells(xlCellTypeConstants)
        With r
            If .Value = "MyText" Then
                If .NumberFormat = "0.00%" Then
                    .ClearContents
                    .NumberFormat = "General"
                End If
            End If
        End With
    Next r
End Sub

编辑#1:

这个版本可能会快一点:

Sub FixingDataFast()
    Dim r As Range, rUnion As Range
    Dim calcM

    Set rUnion = Nothing
    calcM = Application.Calculation
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    For Each r In ActiveSheet.Cells.SpecialCells(xlCellTypeConstants)
        If r.Value = "MyText" Then
            If r.NumberFormat = "0.00%" Then
                If rUnion Is Nothing Then
                    Set rUnion = r
                Else
                    Set rUnion = Union(rUnion, r)
                End If
            End If
        End If
    Next r

    If rUnion Is Nothing Then
    Else
        rUnion.ClearContents
        rUnion.NumberFormat = "General"
    End If

    Application.ScreenUpdating = True
    Application.Calculation = calcM
End Sub

【讨论】:

  • 如果我运行您的代码,我会在第一个If遇到错误,因为它遇到满足条件的第一个单元格。如果我将 .Value 更改为 Formula 它运行良好
  • 另外,它运行速度很慢:在我的测试文件上,使用循环需要 10 秒;但是,通过宏执行 2 次查找和替换(一次用于格式,一次用于文本)只需不到 1 秒。
  • @horace_vr 我试图只更改 both 匹配文本和匹配格式的单元格,而不是所有具有 % 格式的单元格;也许我不明白你想要什么............我不明白为什么 .Value 失败而 .Formula 有效??
  • @horace_vr 我还是不知道为什么.Value 失败了。
  • 你的循环逻辑很好 - 我需要两个条件;我只是在比较跑步所需的时间;生成 2 Find&Replaces 的宏也会执行一些不需要的替换。 .value 的事情也让我感到困惑......
猜你喜欢
  • 1970-01-01
  • 2014-03-17
  • 2013-03-10
  • 2017-11-11
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
相关资源
最近更新 更多