excel - 按列标题搜索和替换
问题描述
抱歉……我的 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
提前致谢。
解决方案
尝试:
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
.
推荐阅读
- python - Python:根据分组生成频率(总和和计数)
- security - OpenAPI 定义是否应该公开?
- android - Lint 在组装发布目标时发现致命错误,添加语言 xml 文件
- php - unlink(/home/goode/public_html/private/uploads/405/):是一个目录,虽然file_exist被检查
- angular - 使用嵌套的 for 循环了解 Angular 的生命周期钩子和模板
- php - 使用 PHP 和 SQL Server 的登录脚本
- kentico - 扩展管理员用户网格 Kentico 10 的列
- php - 文件夹 public/vendor 没有通过 cf push 上传
- java - Google Guice 依赖注入 - 对象究竟是在哪里创建的?
- javascript - 在 Sharethis 的电子邮件中添加主题?