2016-11-22 220 views
0

我是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),但我得到了同樣的錯誤。

回答

0

如果您從單元格中的公式調用此函數,Excel將不允許您從函數內部更改另一個單元格的值。使用Set localRange=pRange不會創建您可以操作的pRange的副本。

也許你應該做的是讓普蘭奇成變量數組和操作這些,那麼的

dim localRange as variant 
localRange=pRange.value2 

代替localRange.Cells(j,1)使用localRange(j,1)

+0

感謝查爾斯,這正是問題。 –

0

這裏是我可以告訴你你的代碼:

  1. 你的問題是在這裏:

    localRange.Cells(j, 1).Value = ""

的值不能爲 「」。嘗試使用localRange.Cells(j, 1).Text = ""

  1. 請勿在VBA中使用整數。 Why Use Integer Instead of Long?

  2. 如果你不能用punkt 1重寫你的代碼,那麼給出一些輸入和輸出的例子,並且StackOverflow中的人會給你提示。

這就是全部:)乾杯!