簡體   English   中英

在將名稱添加到列表時,如何分配單元格的內部隨機顏色?

[英]How to assign random interior color of cells as I add names to a list?

這是我的第一次發貼,所以請留意! 我嘗試將隨機顏色分配給名稱列表,以便稍后可以回憶並填充人員編制表的另一個列表。

到目前為止,這是我的代碼,但由於某些奇怪的原因而無法正常工作。 我不確定是否有人已經問過這個問題,但我的搜索卻空手而歸。

謝謝!

Private Sub Worksheet_Change(ByVal Target As Range)
    Set WF = Application.WorksheetFunction
    If Target.Cells.Column = 1 Then
        If Target.Column = 3 Then
            x = 0
            On Error Resume Next
            x = WF.Match(Target.Value, _
                Range("C1").Resize(Target.Row - 1), _
                0)
            On Error GoTo 0
            If x > 0 Then
                ' duplicate value...copy the old color
                Target.Interior.Color = Cells(x, 3).Interior.Color
            Else
                ' choose a new color
                Target.Interior.Color = RGB( _
                    WF.RandBetween(0, 255), _
                    WF.RandBetween(0, 255), _
                    WF.RandBetween(0, 255))
            End If
        End If
    End If
End Sub
  1. 切勿使用Application.WorksheetFunction.Match或WorksheetFunction.Match。 使用Application.Match並將結果傳遞回變量類型var,可以使用IsError對其進行檢查而不會破壞任何內容。
  2. 如果可以輕松避免,請不要使用On Error Resume Next 參見#1。
  3. 聲明您的var。 更好的是,進入VBE的“工具”,“選項”,然后在“要求變量聲明”旁邊打勾。 這會將Option Explicit放在每個新代碼表的頂部。 啟用后,將Option Explicit放在每個現有代碼表的頂部。
  4. 目標很可能不只是一個單元格,否則例程將失敗。 應用一些錯誤控制,並處理一個以上的目標單元。
  5. 老實說,我不理解如何同時Target.Cells.Column = 1和Target.Column = 3,所以我將只使用后者,因為您正試圖匹配該列。
  6. 在您的情況下,您可以在整個列中查找目標值,並且將始終找到該目標值。 如果在目標上方的一行中找到它,則您有重復的值。

     Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Columns(3)) Is Nothing Then Dim t As Range, x As Long For Each t In Intersect(Target, Columns(3)) Debug.Print t.Address(0, 0) 'looking in the entire column means it will ALWAYS be found x = Application.Match(t.Value, Columns(3), 0) If x < t.Row Then ' duplicate value...copy the old color t.Interior.Color = Cells(x, 3).Interior.Color Else ' choose a new color t.Interior.Color = RGB( _ Application.RandBetween(0, 255), _ Application.RandBetween(0, 255), _ Application.RandBetween(0, 255)) End If Next t End If End Sub 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM