excel - 如果满足条件,则将公式转换为值
问题描述
我想将公式转换为 col P (ReportedGrossActivityReduction) 中的值,用于 col W (test) 为 Yes 的行。
我通过录制创建了以下宏,并在网上搜索后修改。
Sub q()
Dim a As Range
Dim b As Range
Dim c As Range
Set a = Range("W2").Value
Set b = Range("P2").Value
With ActiveSheet
For Each b In .Range("P2")
If a.Range("W2").Value = "Yes" Then
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next
End With
End Sub
解决方案
这是一个“无循环”解决方案,仅将公式结果保留在对应列 W 单元格内容为“是”的 P 列单元格中:
Sub Main()
Dim vals As Variant 'declare a Variant where to store an array
With Range("W2", Cells(Rows.Count, "W").End(xlUp)) ' reference column W range from row 2 down to last not empty one
vals = .Value ' store referenced range values
.Replace what:="Yes", replacement:=1, lookat:=xlWhole ' replace referenced range "Yes" content with a numeric one (1) to exploit subsequent SpecialCells method usage
With .SpecialCells(xlCellTypeConstants, xlNumbers).Offset(, -7) 'reference column P cells corresponding to referenced range cells with numeric content
.Value = .Value ' leave formula result only
End With
.Value = vals ' write back original referenced range values
End With
End Sub
推荐阅读
- wordpress - Woocommerce 数量范围运费
- azure-web-app-service - 将 BLOB 容器挂载为 AppService 中的目录
- docker - 如何访问 Dockerfile 中 docker-compose 的卷挂载的文件?
- android - ListView 元素扩展过多
- java - JDK 17 外存 API 引发异常 - 方法引发“java.lang.UnsatisfiedLinkError”异常
- javascript - 尽管使用 200 个响应代码获取静态文件,但 Django 并未设置页面样式
- typescript - 如何使用 VS Code 扩展 API 动态突出显示变量名?
- visual-studio - 如何从 Dacpac for Azure Pipeline CI/CD 中自动排除仅开发表?
- r - 如何将 for 循环中生成的数据组合成一个散点图?
- ssms - Microsoft SQL Server 管理工作室