[英]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
更改變量類型Integer
或Long
,如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
並通過給其地址聲明您的范圍。
Cells
是Range
對象的集合, Rows
和Columns
。 每當遍歷Range.Rows
並且一行中有多於一列時, .Value
屬性將是一個數組,並且您不能將一個賦值給字符串變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.