gpt4 book ai didi

excel - 在 Sub VBA 中调用用户定义的函数

转载 作者:行者123 更新时间:2023-12-03 03:14:01 24 4
gpt4 key购买 nike

我是 VBA 新手。我目前正在尝试对用户定义的函数应用循环。定义的函数如下。

  Function CountColor(InRange As range, ColorIndex As Long, _
Optional OfText As Boolean = False) As Long
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' CountColor
' This function counts the cells in InRange whose ColorIndex
' is equal to the ColorIndex parameter. The ColorIndex of the
' Font is tested if OfText is True, or the Interior property
' if OfText is omitted or False. If ColorIndex is not a valid
' ColorIndex (1 -> 56, xlColorIndexNone, xlColorIndexAutomatic)
' 0 is returned. If ColorIndex is 0, then xlColorIndexNone is
' used if OfText is Fasle or xlColorIndexAutomatic if OfText
' is True. This allows the caller to use a value of 0 to indicate
' no color for either the Interior or the Font.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim R As range
Dim N As Long
Dim CI As Long

If ColorIndex = 0 Then
If OfText = False Then
CI = xlColorIndexNone
Else
CI = xlColorIndexAutomatic
End If
Else
CI = ColorIndex
End If


Application.Volatile True
Select Case ColorIndex
Case 0, xlColorIndexNone, xlColorIndexAutomatic
' OK
Case Else
If IsValidColorIndex(ColorIndex) = False Then
CountColor = 0
Exit Function
End If
End Select

For Each R In InRange.Cells
If OfText = True Then
If R.Font.ColorIndex = CI Then
N = N + 1
End If
Else
If R.Interior.ColorIndex = CI Then
N = N + 1
End If
End If
Next R

CountColor = N


End Function

我正在尝试在 Sub 中使用此函数 CountColor。但它会抛出运行时 424 错误。

Sub Summary()    
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
LastRow = Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To LastRow
TOTALFAILS = CountColor((range(Cells(i, 4), Cells(i, LastColumn))), 38)
Cells(i, LastColumn + 8) = TOTALFAILS

Next i
End Sub

你能帮我找出我做错了什么吗?任何帮助将不胜感激。谢谢

最佳答案

函数调用方式多了一个“(”,导致获取不到正确的参数,试试这个:

CountColor(Range(Cells(i, 4), Cells(i, LastColumn)), 38)

要确保传递预期参数,请在联机时按 Ctrl + I。 VBEditor 会有所帮助:

enter image description here

一般来说,每当使用 Range()Cells() 对象时,请确保引用它们的工作表和工作簿,to avoid 1004 errors 。在本例中,它应该是这样的:

With ThisWorkbook.Worksheets(1)
For i = 2 To LastRow
TOTALFAILS = CountColor(.Range(.Cells(i, 4), .Cells(i, LastColumn)), 38)
.Cells(i, LastColumn + 8) = TOTALFAILS
Next i
End With

关于excel - 在 Sub VBA 中调用用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com