vba - 根据文字颜色形状

标签 vba excel

我有一张包含多个带有文本字符串的形状的工作表,我想根据其文本为这些形状着色。这是我的代码,目前它无法按预期工作。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim shp As Shape, r As Long, g As Long, b As Long, NormScale As String

With ActiveSheet
    For Each shp In .Shapes
        With shp.TextFrame
            Select Case NormScale
            Case "N"
                r = 255
                g = 0
                b = 0
            Case "P"
                r = 128
                g = 128
                b = 128
            End Select
        End With
        shp.Fill.ForeColor.RGB = RGB(r, g, b)
    Next shp
End With

End Sub

最佳答案

您只是忘记阅读文字:

Sub Mike()

Dim shp As Shape, r As Long, g As Long, b As Long, NormScale As String

With ActiveSheet
    For Each shp In .Shapes
        With shp.TextFrame
            NormScale = .Characters.Text
            Select Case NormScale
            Case "N"
                r = 255
                g = 0
                b = 0
            Case "P"
                r = 128
                g = 128
                b = 128
            End Select
        End With
        shp.Fill.ForeColor.RGB = RGB(r, g, b)
    Next shp
End With

End Sub

编辑#1:

要从流程中排除特定的形状,我们必须首先识别,然后:

Sub WhatDoWeHave()
Dim shp As Shape
With ActiveSheet
    For Each shp In .Shapes
        MsgBox shp.Type & vbCrLf & shp.Name
    Next shp
End With
End Sub

编辑#2:

此版本将排除名称以“Picture”开头的形状

Sub Mike()

Dim shp As Shape, r As Long, g As Long, b As Long, NormScale As String

With ActiveSheet
    For Each shp In .Shapes
        If InStr(shp.Name, "Picture") = 0 Then
            With shp.TextFrame
                NormScale = .Characters.Text
                Select Case NormScale
                Case "N"
                    r = 255
                    g = 0
                    b = 0
                Case "P"
                    r = 128
                    g = 128
                    b = 128
                End Select
            End With
            shp.Fill.ForeColor.RGB = RGB(r, g, b)
        End If
    Next shp
End With

End Sub

关于vba - 根据文字颜色形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27227394/

相关文章:

excel - 使用 Resume Next 循环中的错误处理

vba - 将变量传递给函数并返回 VBA

excel - 如何在 VBA 中使用 FileSystemObject?

mysql - 如何通过检查Excel中的列使用vba从access中提取数据到excel

excel - 使用 Excel VBA 控制 Internet Explorer 本地 Intranet

excel - workbooks.connections.add2 给出运行时错误 5 : Invalid procedure call or argument

excel - 组合多个 IF 公式

Excel 2016 - 引用表中的特定行

excel - 将图表导出为图像 - 只需单击按钮

vba - 在 Excel 中列出文件夹和子文件夹中的所有文件