[英]Identifying and counting elements of the same value in an array Excel VBA
我想計算數組txt中的“ c”數。 從1到0的過渡意味着一個新的周期,這就是為什么無論何時發生此情況,我都將其置於“ c”的原因。 在這段代碼中,當我嘗試計算“ c”時,我得到類型不匹配的信息。 感謝您的幫助。
Sub CopyColumn()
Dim finalrow As Long
Dim i As Variant
ReDim arrayciclos(0)
Dim str As String
Dim ciclos As Variant
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To finalrow
arrayciclos(UBound(arrayciclos)) = Range("J" & i)
ReDim Preserve arrayciclos(UBound(arrayciclos) + 1)
Next i
For i = LBound(arrayciclos) To UBound(arrayciclos)
txt = txt & arrayciclos(i) ' & vbCrLf
Next i
MsgBox txt
Do While InStr(txt, "10")
txt = Replace(txt, "10", "c")
Loop
MsgBox txt
ciclos = 0: i = 0
For i = 0 To finalrow
If txt(i) = "c" Then ' i have Type Mismatch here
ciclos = ciclos + 1
End If
Next
MsgBox (ciclos)
End Sub
我認為您使用的循環過多。 如果要遍歷數組txt要計算“ c”的數量,則只需執行
Dim MyArray As Variant
dim count as integer
'specify your range. For example
MyArray = Range("BS27:DS50000")
'Loop through and find all occurrences of "c"
For i = LBound(MyArray) To UBound(MyArray)
For j = LBound(MyArray, 2) To UBound(MyArray, 2)
If MyArray(i, j) = "c" Then count = count + 1
Next j
Next i
msgbox count
如果每個單元格中的“ c”不是單個,則將If MyArray(i,j)=“ c”替換為If MyArray(i,j)=“ c”,然后將asterix放在asterix c asterix之類的“ c”兩側。 這將是一個字符匹配
根據您發布的代碼,沒有明確聲明txt
變量。 另外,當您使用第二個循環將值與txt = txt & arrayciclos(I)
串聯在一起時,variant的隱式聲明成為字符串的一種類型。 您應該修改代碼以包含Option Explicit
語句,以檢查未聲明的變量。 另外,您應該使用Mid
函數在最終循環中執行對“ c”字符的檢查。
Option Explicit ' <-- added to check for undeclared variables
Sub CopyColumn()
Dim finalrow As Long
Dim i As Variant
ReDim arrayciclos(0)
Dim str As String ' <-- unused variable problaby should have been named txt in your example
Dim ciclos As Variant
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
finalrow = 9
For i = 2 To finalrow
arrayciclos(UBound(arrayciclos)) = Range("J" & i)
ReDim Preserve arrayciclos(UBound(arrayciclos) + 1)
Next i
For i = LBound(arrayciclos) To UBound(arrayciclos)
str = str & arrayciclos(i) ' & vbCrLf
Next i
MsgBox str
Do While InStr(str, "10")
str = Replace(str, "10", "c")
Loop
MsgBox str
ciclos = 0: i = 0
For i = 0 To finalrow
If Mid(str, i + 1, 1) = "c" Then ' <-- changed to Mid(string, start, len)
ciclos = ciclos + 1
End If
Next
MsgBox (ciclos)
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.