2014-09-23 177 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