得到运行时错误“ 13”:当我运行以下宏时,键入不匹配

时间:2019-06-25 10:37:40

标签: excel vba

我是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

我在这里做什么错了?

3 个答案:

答案 0 :(得分:1)

将此行For Each Mycell In Myrange.Rows更改为

For Each Mycell In Myrange

使用Myrange.Rows时,子菜单将循环到您设置范围的行。当您仅使用Myrange时,它将循环到设置范围的单元格。同时从.value中删除Mycell.Value,因为当您使用.value时,它将仅从单元格中获取值(数字值)。如果您想保留.value,则可以像Integer那样从Long更改变量类型StringDim 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)

您正在尝试将数组分配给字符串变量

CellsRange对象的集合,RowsColumns也是如此。每当遍历Range.Rows且一行中有多于一列时,.Value属性将是一个数组,并且您无法将其分配给字符串变量。