簡體   English   中英

得到運行時錯誤“ 13”:當我運行以下宏時,鍵入不匹配

[英]Getting Run-time error '13': Type mismatch when I run following macro

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

我在這里做錯了什么?

更改For Each Mycell In Myrange.Rows

For Each Mycell In Myrange

當您使用Myrange.Rows ,子項將循環到您設置的范圍的行。 當僅使用Myrange ,它將循環到設置范圍的單元格。 還從Mycell.Value刪除.value ,因為當您使用.value時,它將僅從單元格中獲取值(數字值)。 如果要保留.value則從String更改變量類型IntegerLong ,如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

您無需為單元格值聲明變量,只需執行以下操作即可:

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並通過給其地址聲明您的范圍。

您正在嘗試將數組分配給字符串變量

CellsRange對象的集合, RowsColumns 每當遍歷Range.Rows並且一行中有多於一列時, .Value屬性將是一個數組,並且您不能將一個賦值給字符串變量。

暫無
暫無

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

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