Excel (VBA)

Excel VBAに関するフォーラムです。
  • 解決済みのトピックにはコメントできません。
このトピックは解決済みです。
質問

 
(Windows 11 Pro : Excel 2019)
条件でセル塗りつぶし解除
投稿日時: 23/06/03 10:49:48
投稿者: momo0717

下記のようなマクロを作成したのですが、ステータスを"Done"に変更した場合にセルの塗りつぶし及び文字の太字を無くしたいのにマクロが効きません。何がいけないのでしょうか?
 
Sub UpdateStatusToOverdue()
    Dim rng As Range
    Dim cell As Range
    Dim ws As Worksheet
    Dim statusList As String
 
    ' Define the status list (replace with your actual list if different)
    statusList = "Done,In progress,On hold,Not Started,Overdue"
 
    Set ws = Sheets("ToDoList")
    ' Define the range to check
    Set rng = ws.Range("G5:G100")
 
    ' Remove data validation from H5:H100
    ws.Range("H5:H100").Validation.Delete
 
    ' Check each cell in the range
    For Each cell In rng
        ' If the cell value is negative and the status is not already "Overdue"
        If cell.Value < 0 And cell.Offset(0, 1).Value <> "Overdue" Then
            ' Set the status to "Overdue"
            cell.Offset(0, 1).Value = "Overdue"
            ' Color corresponding C and H cells in light red
            cell.Offset(0, -4).Interior.Color = RGB(255, 153, 153) ' adjust the RGB values as needed
            cell.Offset(0, 1).Interior.Color = RGB(255, 153, 153) ' adjust the RGB values as needed
             
            ' Change the font of G column cell to bold red
            cell.Font.Bold = True
            cell.Font.Color = RGB(255, 0, 0) ' adjust the RGB values as needed
        ElseIf cell.Offset(0, 1).Value = "Done" And cell.Offset(0, -4).Interior.Color <> RGB(255, 255, 255) Then
            ' If the status is "Done" and the cell is not already in default format
            cell.Offset(0, -4).Interior.ColorIndex = xlNone
            cell.Offset(0, 1).Interior.ColorIndex = xlNone
            cell.Font.Bold = False
            cell.Font.Color = RGB(0, 0, 0) ' reset to black
        End If
    Next cell
 
    ' Restore data validation in H5:H100
    With ws.Range("H5:H100").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=statusList
        .IgnoreBlank = True
        .InCellDropdown = True
        .ShowInput = True
    End With
End Sub

回答
投稿日時: 23/06/03 11:37:50
投稿者: simple

ステップ実行して、どこで想定と異なることになるのか、確認されているのでしょうか。
 
・cell.Value
  cell.Offset(0, 1).Value
  cell.Offset(0, -4).Interior.Color
がこのようなケースで、
・想定はこうなるのだが、
・実際にはこうなってしまう、
という説明をしてもらえますか?
 
# 第一の条件に合致してしまって、第二の条件のときの実行がされていないのではないですか?

回答
投稿日時: 23/06/03 12:54:52
投稿者: WinArrow

条件の書き方
 

>If cell.Value < 0 And cell.Offset(0, 1).Value <> "Overdue" Then
このように、条件を「And」で同時に判定すると、
どの条件で間違ていたかを検証することが難しです。
面倒でも、条件は1行に記述した方が分かりやすいし、処理も早いです。
 
If cell.Value < 0 Then
    If cell.Offset(0, 1).Value <> "Overdue" Then
        ’処理
    End If
End if

回答
投稿日時: 23/06/03 13:44:10
投稿者: WinArrow

別提案
 
条件付き書式では対応でいないのでしょうか?
色の条件はできませんが、
色尾を判断して色を消すのではなく、
「ある条件の時に色を付ける」に考えるとでいそうな気がします。

投稿日時: 23/06/07 08:07:11
投稿者: momo0717

アドバイスありがとうございました。
条件付き書式にて対応することにしました。