2016-12-30 94 views
1

我寫了一個函數,但由於某種原因它不起作用。我調試了,但仍然沒有發生什麼事。我寫了一些其他功能來理解什麼不起作用,並且我得出結論認爲activecell是有問題的部分。由於某些原因,當我寫入函數activecell。未被檢測到。 我在下面寫了我的代碼。該函數有兩個參數:r(只是一列的範圍,換句話說就是Ai:Aj)和名稱(它必須是一個字符串),這個函數應該做的是計算最長的外觀不斷名字,換句話說,如果我有一個有值進入細胞中,A,b,A,A,A,如果NAME =一則函數將返回3.VBA for Excel,activecell在編寫函數時不起作用

Function cont(r As range, name As String) As Integer 
Dim count As Integer, l As Integer 
r.Cells(1).Activate 
l = 0 
count = 0 
Do While IsEmpty(ActiveCell) = False 
    If ActiveCell.Value <> name Then 
     ActiveCell.Offset(1, 0).Activate 
    Else 
     Do While ActiveCell.Value = name 
      count = count + 1 
      ActiveCell.Offset(1, 0).Activate 
     Loop 
     If count >= l Then l = count 
    End If 
    count = 0 
Loop 
cont = l 
End Function 

我擡頭看看其他人是否有類似的問題,但我找不到有用的東西。也許有人在這裏可以告訴我什麼是錯的?謝謝!

+2

Scott提供了一個答案,但是爲了解釋爲什麼你的代碼不工作,UDF不能改變'ActiveCell',所以你的行'r.Cells(1).Activate'什麼都不做,並且'ActiveCell'仍然是觸發對'cont'的調用的單元格,如果您輸入/更新它,它將成爲發生'= cont(...)'的單元格(因此會給出一個循環參考錯誤),或者你的'r'範圍內被更改的單元格。 (如果單元格中包含「name」的值,則可能會出現無限循環,或者至少是循環,直到count變爲32767.) – YowE3K

回答

2

不要使用激活或者選擇只要有可能,只是通過輸入範圍迭代,並對其進行測試:

Function cont(r As Range, name As String) As Integer 

Dim i&, j&, cnt& 
For i = 1 To r.Rows.count 
    If r(i, 1).Value = name Then 
     For j = i To r.Rows.count 
      If r(j, 1).Value <> name Then 
       Exit For 
      Else 
       cnt = cnt + 1 
      End If 
     Next j 
     If cnt > cont Then cont = cnt 
     cnt = 0 
     i = j 
    End If 
Next i 

enter image description here


僅用一個循環再去做

Function cont(r As Range, name As String) As Integer 

Dim i&, cnt&, tst As Boolean 
For i = 1 To r.Rows.count 
    If r(i, 1).Value = name And tst = True Then 
     cnt = cnt + 1 
    ElseIf r(i, 1).Value = name And tst = False Then 
     tst = True 
     cnt = 1 
    Else 
     tst = False 
     If cont < cnt Then cont = cnt 
    End If 
Next i 
If cont < cnt Then cont = cnt 

End Function 

有關避免選擇和激活的更多信息,請點擊此處:How to avoid using Select in Excel VBA macros

+0

Scott,您的代碼計算範圍內的所有名稱外觀,OP只想保持連續的出現 –

+0

@ShaiRado yup,你是對的,看看編輯。 –

+0

謝謝!這幫助我解決了這個問題! –