【问题标题】:vba runtime error 424 object required - string indexingvba 运行时错误 424 需要对象 - 字符串索引
【发布时间】:2014-04-02 16:35:34
【问题描述】:

我查看了其他链接,但似乎没有一个可以帮助我。我正在为一个程序编写代码,该程序将计算一个短语中的所有逗号。我不是编程新手,但我是 VBA 新手。

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 

【问题讨论】:

    标签: vba excel runtime-error


    【解决方案1】:
    1. 将j = s.Chars(i) 更改为j = Mid(s,i,1)
    2. 在Dim i, my_c As Integer 中只有my_c 是Integer,但i 是Variant。您应该明确声明每个变量:Dim i As Integer, my_c As Integer
    3. 不确定您的Count 到底是什么(可能是文本框),但请使用 Count.Text = my_c 不带引号。
    4. 我也无法理解你为什么要使用两个循环? While i &lt; 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
      

      【讨论】:

        猜你喜欢
        • 2013-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-01
        • 1970-01-01
        相关资源
        最近更新 更多