简体   繁体   English

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

[英]Excel VBA Function For Each Cell in Selection error resulting to Variable Not Defined

I was writing A code function in excel that calls a subroutine after the function gets the input data. 我在excel中编写一个代码函数,该函数在获取输入数据后调用子例程。 The function is to color a cell or range of cells within a worksheet or another worksheet using the RGB values in the excel. 该功能是使用Excel中的RGB值为工作表或另一个工作表中的一个单元格或单元格区域着色。

However, I do not know how to call the cell values with the function I wrote once the subroutine is working. 但是,一旦子例程开始工作,我不知道如何使用我编写的函数调用单元格值。 The Error says Variable not Defined. 错误显示变量未定义。 Looks like the "For Each Cell in Selection" line is causing the error, as the cell is not declared once I passed the data of the function to the subroutine. 看起来是“对于选择中的每个单元格”这行引起了错误,因为一旦将函数的数据传递给子例程,就没有声明该单元格。 Also, can someone provide the code on modifying other worksheet's cells in the form of: "Cell.Interior.Color = RGB(Red, Green, Blue)"? 另外,有人可以以“ Cell.Interior.Color = RGB(Red,Green,Blue)”的形式提供修改其他工作表单元格的代码吗? The worksheet's name is provided to be input by the user. 提供工作表的名称以供用户输入。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM