[英]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.