2014-04-02 102 views
0

我看了其他链接,似乎没有人帮助我。我正在编写一个程序的代码,将计算一个短语中的所有逗号。我对编程并不陌生,但我是VBA的新手。vba运行时错误424所需的对象 - 字符串索引

Sub examp() 

Dim s As String 

Dim i, my_c As Integer 

i = 0 

s = ",jkqk;j,oiheqfjnq;ef,jwhef;ur,jwefun;jwkbnf," '<-------arbitrary, however, when I tried to make it input from a textbox it gave me error 424 as well, so I just defined it as random chars with commas 

While i < Len(s) 

    For i = 0 To Len(s) - 1 

    j = s.Chars(i) <----------------------------------Error occurs here 
     If j = "," Then 
      my_c = my_c + 1 
    End If 
    Next i 
Wend 

Count.Text = "my_c" 

End Sub 

回答

3
  1. 变化j = s.Chars(i)j = Mid(s,i,1)
  2. 符合Dim i, my_c As Integer只有my_cInteger,但iVariant。您应该明确声明每个变量:Dim i As Integer, my_c As Integer
  3. 不确定您的Count(可能是文本框)到底是什么,但使用 Count.Text = my_c不带引号。
  4. 我也无法理解你为什么使用两个循环? While i < Len(s) 很奇怪。
  5. For i = 0 To Len(s) - 1应该For i = 1 To Len(s)

如果你想算逗号,没有更有效的方法:

Dim s As String 
Dim my_c As Integer 
s = ",jkqk;j,oiheqfjnq;ef,jwhef;ur,jwefun;jwkbnf," 
my_c = Len(s) - Len(Replace(s, ",", "")) 
2

或者你可以试试这个:

Sub test() 

Dim s As String 
Dim c 
Dim my_c As Long 

s = ",jkqk;j,oiheqfjnq;ef,jwhef;ur,jwefun;jwkbnf," 
c = Split(s, ",") 
my_c = UBound(c) 
Debug.Print my_c 

End Sub 
相关问题