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

标签 excel vba

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

但是,一旦子例程开始工作,我不知道如何使用我编写的函数调用单元格值。错误说 undefined variable 。看起来“对于选择中的每个单元格”行导致了错误,因为一旦我将函数的数据传递给子例程,就没有声明单元格。
另外,有人可以以“Cell.Interior.Color = RGB(Red, Green, Blue)”的形式提供修改其他工作表单元格的代码吗?工作表的名称由用户输入。

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 :Dim Cell As Range在您的 SubCalculateColor() 的开头。

关于选择错误中每个单元格的 Excel VBA 函数导致变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28582557/

相关文章:

asp.net - Filehelpers Excel 到 Oracle db

vba - 读取 Excel 文件的 VBA 宏(或 vbaProject.bin),而无需在 MS Excel 中打开它

excel - 加载 csv "Could not find installable ISAM"

excel - 在 VBA Excel 中以 PDF 格式打印的可变垂直页数

parsing - Excel vba解析公式

excel - 如何从vba写入excel

vba - 使用公共(public)列合并两个 Excel 文件

javascript - JavaScript 中的金融利率功能无法正常工作

vba - 使用条件格式扩展行组时 Excel 卡住

excel - 从托管的 HP 质量中心导出错误跟踪数据的最佳方式是什么?