excel - vba中的Instr不使用公式单元格
问题描述
我有一个单元格(例如 L22),其中有一个公式(引用另一张表(Sheet!1A22)并返回值 sale 110(108%)。我只想更改(108%)的文本颜色(而不是整个单元格值)。我的方法是使用 Instr 查找“(”并找到直到“)”的长度并为其着色。这是我使用的代码。
Sub colr()
Dim StartChar As Integer, LenColor As Integer
With Flash.Range("L22")
StartChar = InStr(1, .Value, "(")
If StartChar <> 0 Then
LenColor = Len(.Value) - StartChar + 1
.Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
End If
End With
End Sub
但代码没有做任何事情。但是如果我用值替换公式,它就可以正常工作。
解决方案
正如其他人所评论的那样,不可能操纵Characters
公式的结果 - 至少据我所知不是。
最明显的替代方法是在两个相邻单元格中写入值和百分比,然后对后者使用条件格式。
但是,如果您坚持使用现有格式,那么您将不得不解决公式问题。当任何引用的范围值发生更改时,基本上都会触发公式计算。您可以自己捕获该事件,例如在Worksheet_Change
处理程序中并将算法的结果写入 Sheet2。这将使您能够为结果的字符着色。
骨架代码看起来像这样(在 Sheet1 对象中):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim result As Variant
Dim pt As Long
For Each cell In Target.Cells
'Test for a change in the desired range.
If Not Intersect(cell, Me.Range("A:A")) Is Nothing Then
'Check that your cell value matches the conditions you want, eg
If IsNumeric(cell.Value) Then
'Calculate the result - as per your cell formula.
result = cell.Value * 2 & " (" & cell.Value * 2 / 100 & "%)"
'Write and colour the result.
pt = InStr(result, "(")
With Sheet2.Cells(cell.Row, "L")
.Value = result
.Characters(pt, Len(result)).Font.Color = RGB(255, 0, 0)
End With
End If
End If
Next
End Sub
推荐阅读
- ios - 使用 UIScrollView 显示 CarouselImagesView
- ruby-on-rails - 在没有 webpack 的情况下使用 ActionText
- typescript - 为什么我不能将函数表达式注释为 void,尽管它在 TypeScript 中不返回任何内容?
- android - 如何指定要使用 Fastlane 更新的应用程序(在 Google Play 控制台中创建)?
- spring-boot - 无法将 Spring Boot 应用程序部署到 WebLogic 服务器
- docker - 使用 heroku.yml 部署到 Heroku 多个 docker 映像,收到错误:无法检测到此应用的默认语言
- python - if else on dataframe header 给出 KeyError
- ruby - 无法理解 Ruby 中实例变量的范围
- multithreading - RestTemplate.exchange:锁定线程
- api - Google Data Studio 是否具有 API 功能,如果没有,是否会在不久的将来提供?