我是VBA的新手,我对语法不太熟悉。我做了一个excel宏,它将识别当前单元格的背景,并将当前值附加背景颜色的名称。因此,如果一个单元格具有蓝色背景且值为1000,则宏应将单元格中的值替换为“ 1000 blue”。以下是我编写的代码。
Sub coloridentifier()
Dim Myrange As Range
Dim Mycell As Range
Dim Myvalue As String
Set Myrange = Selection
For Each Mycell In Myrange.Rows
Myvalue = Mycell.Value
If Mycell.Interior.Color = RGB(0, 176, 80) Then
Mycell.Value = Myvalue & " Green"
ElseIf Mycell.Interior.Color = RGB(184, 204, 228) Then
Mycell.Value = Myvalue & " Blue"
ElseIf Mycell.Interior.Color = RGB(192, 0, 0) Then
Mycell.Value = Myvalue & " Red"
End If
Next Mycell
End Sub
调试器指向以下行:
Myvalue = Mycell.Value
我在这里做什么错了?
答案 0 :(得分:1)
将此行For Each Mycell In Myrange.Rows
更改为
For Each Mycell In Myrange
使用Myrange.Rows
时,子菜单将循环到您设置范围的行。当您仅使用Myrange
时,它将循环到设置范围的单元格。同时从.value
中删除Mycell.Value
,因为当您使用.value
时,它将仅从单元格中获取值(数字值)。如果您想保留.value
,则可以像Integer
那样从Long
更改变量类型String
或Dim Myvalue As Integer
。
因此,完整子将为
Sub coloridentifier()
Dim Myrange As Range
Dim Mycell As Range
Dim Myvalue As Variant
Set Myrange = Selection
For Each Mycell In Myrange
Myvalue = Mycell
If Mycell.Interior.Color = RGB(0, 176, 80) Then
Mycell.Value = Myvalue & " Green"
ElseIf Mycell.Interior.Color = RGB(0, 0, 255) Then
Mycell.Value = Myvalue & " Blue"
ElseIf Mycell.Interior.Color = RGB(192, 0, 0) Then
Mycell.Value = Myvalue & " Red"
End If
Next Mycell
End Sub
答案 1 :(得分:1)
您无需为单元格值声明变量,只需执行以下操作即可:
Option Explicit
Sub coloridentifier()
Dim Myrange As Range
Dim Mycell As Range
Set Myrange = Selection
For Each Mycell In Myrange
If Mycell.Interior.Color = RGB(0, 176, 80) Then
Mycell = Mycell & " Green"
ElseIf Mycell.Interior.Color = RGB(184, 204, 228) Then
Mycell = Mycell & " Blue"
ElseIf Mycell.Interior.Color = RGB(192, 0, 0) Then
Mycell = Mycell & " Red"
End If
Next Mycell
End Sub
尽管我会避免使用Set Myrange = Selection
并通过给其地址声明您的范围。
答案 2 :(得分:0)
Cells
是Range
对象的集合,Rows
和Columns
也是如此。每当遍历Range.Rows
且一行中有多于一列时,.Value
属性将是一个数组,并且您无法将其分配给字符串变量。