简体   繁体   中英

Excel 2010 - Macro to Detect Specific Interior Color of a Cell and Produce a Result

I created an Excel spreadsheet with a command button that calls a macro. The macro produces an new email through Microsoft Outlook that provides a list of data, specifically data from cells ranged A5 through A500 that have an interior color of RGB(255, 255, 204).

However, I'm not getting accurate results. The macro is not exclusively capturing the data from cells of the specified interior color and is giving me data from cells of alternate colors as well. This may be a logic error on my part.

Here is the code I am currently working with:

Private Sub btnReport_Click()
'Create Email Message
Dim r As Range
Dim m As String
Set r = ActiveSheet.Range("A5:A500")
m = "Hello,<br><br>Here is some information:<br><br>" & _
    "<table border=""1"" style=""width:98.7%"" align=""left"" ><tr style=""vertical-align:top;""><td style=""width:9.3%"" nowrap>" & _
    "<b>Column 1</b></td><td style=""width:10%"" nowrap><b>Column 2</b></td><td style=""width:10%"" nowrap><b>Column 3</b></td></tr>"

For Each r In r.Cells
    If r.Interior.Color = RGB(255, 255, 204) Then
        m = m & "<tr><td>" & ActiveSheet.Range("D" & r) & "</td><td>" & ActiveSheet.Range("L" & r) & "</td><td>" & _
            ActiveSheet.Range("M" & r) & "</td></tr>"
    End If
Next

'Open Email
Dim olApp As Object
Dim olMail As Object
Dim name As String

Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(olMailItem)
With olMail
    .To = "Dee Wolf"
    .Subject = "This is a subject line"  
    .HTMLBody = m
    .Display
End With
Set olMail = Nothing
Set olApp = Nothing

End Sub

Why are you using the r variable twice for 2 purposes, and why are you building a range using ("D" & r). r is an object (specifically a cell). I am assuming you want to take data from D and M, but on the same row?

If so this should read as below.

Dim aCell as Range

For Each aCell In r.Cells
    If r.Interior.Color = RGB(255, 255, 204) Then
        m = m & "<tr><td>" & ActiveSheet.Range("D" & aCell.Row) & "</td><td>" & ActiveSheet.Range("L" & aCell.Row) & "</td><td>" & _
            ActiveSheet.Range("M" & aCell.Row) & "</td></tr>"
    End If
Next

You may of course be taking a shortcut, and actually are using r.Value when you build a range using Range("D" & r). ie this is shot for Range("D" & r.Value)...so if "r" references a cell with a number in it like 599, then you want to reference cell "D599" which is what your code does?

这对我有用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM