VBA代码,用于根据单元格中的值更改形状的填充颜色

时间:2017-11-21 12:56:36

标签: excel vba excel-vba

    <!doctype html>
<html lang="pt_BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Admin</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="row">
    <div class="col-sm-12 col-md-12">
        <h2 class="text-center">Admin</h2>
        <hr>
    </div>
</div>
    <div class="row">
        <div class="col-sm-4 col-md-2 col-md-offset-5 col-sm-offset-4">
            <form action="{{ route('painel.auth.store') }}" method="post" id="login-form">

                {!! csrf_field() !!}

                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" class="form-control" name="email" id="email" placeholder="Email">
                </div>
                <div class="form-group">
                    <label for="password">Senha</label>
                    <input type="password" class="form-control" name="password" id="password" placeholder="Senha">
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-lg btn-block" name="submit" id="submit">Entrar</button>
                </div>
            </form>
        </div>
    </div>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

在单元格E9中,我有以下公式:

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("E9")) Is Nothing Then Exit Sub
    If IsNumeric(Target.Value) Then
        If Target.Value < 0 Then
            ActiveSheet.Shapes("Rectangle 2").Fill.ForeColor.RGB = vbRed
        Else
            ActiveSheet.Shapes("Rectangle 2").Fill.ForeColor.RGB = vbGreen
        End If
    End If
End Sub

这似乎不起作用,只有我在E9中手动编写例如500。 任何解决方案?

1 个答案:

答案 0 :(得分:1)

当通过公式更改单元格内容时,不会触发工作表更改事件。要实现这一点,您需要使用Sheet Calculate Event。

试一试。将以下代码放在图纸模块上。

Private Sub Worksheet_Calculate()
Dim cell As Range
Set cell = Range("E9")
If IsNumeric(cell) Then
    If cell.Value < 0 Then
        ActiveSheet.Shapes("Rectangle 2").Fill.ForeColor.RGB = vbRed
    Else
        ActiveSheet.Shapes("Rectangle 2").Fill.ForeColor.RGB = vbGreen
    End If
End If
End Sub