在函数中操作类型Range的参数(VBA - excel)
问题描述:
我是VBA的新手,并且遇到了一些问题,特别是在语法方面。我试图做一个函数,计算有多少重复的单元格,我有一个通过范围内(现在,我假设应该只通过1列的范围)。在函数中操作类型Range的参数(VBA - excel)
我有以下几点:
Public Function countRepeated(ByVal pRange As range) As Integer
Dim numberOfRows As Integer
Dim numberOfColumns As Integer
Dim repeated As Integer
Dim localRange As range
Set localRange = pRange
numberOfRows = localRange.Rows.Count
numberOfColumns = localRange.columns.Count
If (numberOfColumns > 1) Then
temp = MsgBox("Insira intervalos com apenas 1 coluna.", vbExclamation, "Erro")
countRepeated = -1
Exit Function
End If
repeated = 0
For i = 1 To numberOfRows
temporary = localRange.Cells(i, 1).Value
For j = i + 1 To numberOfRows
If (temporary = localRange.Cells(j, 1).Value And temporary <> "") Then
repeated = repeated + 1
localRange.Cells(j, 1).Value = ""
'after the previous instruction, i get thet #VALUE! error
'i also try set localRange.Cells(j,1).Value = ""
'and localRange.Cells(j, 1).Value = 0
End If
Next j
Next i
countRepeated = repeated
End Function
但我得到一个#VALUE!
错误之后,我试图改变从范围内的值。最初,我试图通过传递'ByVal'来修改参数本身(pRange),但我得到了同样的错误。
答
如果您从单元格中的公式调用此函数,Excel将不允许您从函数内部更改另一个单元格的值。使用Set localRange=pRange
不会创建您可以操作的pRange的副本。
也许你应该做的是让普兰奇成变量数组和操作这些,那么的
dim localRange as variant
localRange=pRange.value2
代替localRange.Cells(j,1)
使用localRange(j,1)
答
这里是我可以告诉你你的代码:
-
你的问题是在这里:
localRange.Cells(j, 1).Value = ""
的值不能为 “”。尝试使用localRange.Cells(j, 1).Text = ""
请勿在VBA中使用整数。 Why Use Integer Instead of Long?
如果你不能用punkt 1重写你的代码,那么给出一些输入和输出的例子,并且StackOverflow中的人会给你提示。
这就是全部:)干杯!
感谢查尔斯,这正是问题。 –