2014-09-23 91 views
0

我想计算数组txt中“c”的数字。 1到0的过渡意味着一个新的循环,这就是为什么当这种情况发生时,我会放一个“c”。在这段代码中,当我尝试计算“c”时,出现类型不匹配。感谢您的帮助。识别和计算数组中相同值的元素Excel VBA

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 
+0

我不检查的代码,但** ** TXT它不是一个数组,你可以不写** TXT(I)** ...... – user3514930 2014-09-23 11:40:06

回答

0

根据您发布的代码,txt变量未明确声明。另外,当您使用第二个循环将值与txt = txt & arrayciclos(I)连接在一起时,变体的隐式声明变为一种字符串类型。您应修改代码以包含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 
0

我认为你使用的循环太多。如果你想通过数组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”是不是每个单元内单再更换如果MYARRAY(I,J)= “c”与If MyArray(i,j)=“c”并将asterix放在“c”的两侧,如asterix c asterix。这将是一个字符匹配

+0

谢谢。这是一个更好的方式。 – diego 2014-09-24 07:51:11

+0

如果它适合你,那么请接受答案 – george 2014-09-24 08:08:26