首页 > 解决方案 > 按列标题搜索和替换

问题描述

抱歉……我的 VBA 技能几乎不存在……

我要做的是在 Excel 中创建一个宏,其中列 (1) 中的数据被列标题(SAND、LS 和 CS)替换。这是一个示例表:

深度 LS CS
600 1 -999 -999
700 -999 -999 1
800 1 -999 -999
900 -999 1 -999

这是我运行宏时的结果:

深度 LS CS
600 -999 -999
700 -999 -999 CS
800 -999 -999
900 -999 LS -999

但是,我需要让 Excel 读取第一行中的Header以替换 1。不是列字母(例如在下面的代码中读取SAND而不是Columns("B:B")。我有很多不同的文件相同的格式,但具有不同的列数和不同的列标题,因此问题。

这是我创建的宏的示例。

Sub LithReplace()
'
' LithReplace Macro
'

'
    Range("B1").Select
    Selection.Copy
    Columns("B:B").Select
    Selection.Replace What:="1", Replacement:="SAND            ", LookAt:= _
        xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
    Range("C1").Select
    Application.CutCopyMode = False
    Selection.Copy
    Columns("C:C").Select
    Selection.Replace What:="1", Replacement:="LS              ", LookAt:= _
        xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
    Range("D1").Select
    Application.CutCopyMode = False
    Selection.Copy
    Columns("D:D").Select
    Selection.Replace What:="1", Replacement:="CS               ", LookAt:= _
        xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
End Sub

提前致谢。

标签: excelvbareplace

解决方案


尝试:

Sub test()
Dim rng As Range
Dim MyColumn As Range
Set rng = Range("A1").CurrentRegion 'dataset. Replace A1 by top left cell reference

For Each MyColumn In rng.Columns
    If MyColumn.Column > 1 Then 'we skip first column
        MyColumn.Replace "1", MyColumn.Cells(1, 1).Value, xlPart 'replace 1 with 'top cell of each column
    End If
Next MyColumn

Set rng = Nothing
End Sub

代码将遍历每一列,并将任何列替换1为每列的顶部单元格值,因此它适用于任何列数量

我在执行代码后得到这个:

在此处输入图像描述

重要提示:考虑使用xlWhole代替xlPart,因为现在如果有任何1它将被替换,所以类似的东西213可以转换为2SAND3.

Range.Replace 方法 (Excel)


推荐阅读