选择错误导致变量未定义的每个单元格的Excel VBA函数

时间:2015-02-18 11:31:14

标签: excel-vba vba excel

我在excel中编写了一个代码函数,在函数获取输入数据后调用子程序。 该功能是使用Excel中的RGB值为工作表或其他工作表中的单元格或单元格区域着色。

但是,我不知道如何在子程序工作后用我写的函数调用单元格值。错误表示变量未定义。看起来像" For Each Cell in Selection" line导致错误,因为一旦我将函数的数据传递给子例程,就不会声明单元格。 此外,有人可以提供修改其他工作表单元格的代码:" Cell.Interior.Color = RGB(红色,绿色,蓝色)"?提供工作表的名称以供用户输入。

Option Explicit
Dim Activate As Boolean

Public Function SETRGBCOLOR( _
    Optional CurrentCellValue As Variant, _
    Optional wksSheetname As String, _
    Optional rngRange As Range, _
    Optional byteRed As Byte = 0, _
    Optional byteGreen As Byte = 0, _
    Optional byteBlue As Byte = 0) As Variant

    If IsMissing(CurrentCellValue) Then
        SETRGBCOLOR = ""
    Else
        SETRGBCOLOR = CurrentCellValue
    End If

    Activate = False

    'set greater RGB values than max RG value to 255, byte ignores the negative value of a digit
    If byteRed > 255 Then byteRed = 255
    If byteGreen > 255 Then byteGreen = 255
    If byteBlue > 255 Then byteBlue = 255

    Activate = True

    Call CalculateColor(wksSheetname, rngRange, byteRed, byteGreen, byteBlue)
End Function

Private Sub CalculateColor(wksSheetname As String, rngRange As Range, byteRed As Byte, byteGreen As Byte, byteBlue As Byte)
    If Activate = True Then

        If Trim(wksSheetname) <> "" Then
            If Trim(rngRange) <> "" Then
                For Each Cell In Selection
                    Cell.Interior.Color = RGB(byteRed, byteGreen, byteBlue)
                Next Cell
            Else
            End If
        Else
            If Trim(rngRange) <> "" Then
                'For Each Cell In Selection
                '    Cell.Interior.Color = RGB(byteRed, byteGreen, byteBlue)
                'Next Cell
            Else
            End If
        End If
    End If
    Activate = False
End Sub

1 个答案:

答案 0 :(得分:2)

您有Option Explicit因此必须声明变量 Cell : 在Sub CalculateColor()的开头Dim Cell As Range