首页 文章

运行时错误9:使用字符串数组时,下标超出范围

提问于
浏览
1

我是vba脚本的新手 . 我正在尝试编写下面的函数,但无法成功完成 . 我真的很感激我能得到的任何帮助 .

代码是:

Option Explicit

Dim status As String

Sub StartModule()
Dim index As Integer
Dim result As String
Dim a As Integer
Dim Name As Variant

Range("D4").Value = 1
Range("D5").Value = 5
Range("D6").Value = 9
Range("D7").Value = 2

Dim o: Set o = CreateObject("NAddIn.Functions")
status = ""

Do Until status = "DADA"
    result = o.getRandomNumber
    Name = Split(result, ",")

    If Trim(Name(3)) = Trim(Range("D4").Value) Then
        Range("C4").Value = "one"
    End If
    If Trim(Name(3)) = Trim(Range("D5").Value) Then
        Range("C5").Value = "five"
    End If
    If Trim(Name(3)) = Trim(Range("D6").Value) Then
        Range("C4").Value = "nine"
    End If
    If Trim(Name(3)) = Trim(Range("D7").Value) Then
        Range("C7").Value = "two"
    End If

    Wait 1 '<~~ Wait for a second
    If status = "EXIT" Then Exit Do
Loop

End Sub

Sub StopModule()
    status = "EXIT"
End Sub

Private Sub Wait(ByVal nSec As Long)
    nSec = nSec + Timer
    While nSec > Timer
        DoEvents
    Wend
End Sub

此vba脚本正在调用 getRandomNumber() ,它是dll文件中的用户定义函数 . 它生成范围(1,10)中的随机数字符串;然后将字符串中的thrid随机数与excel中的单元格值进行比较,以使用某些字符串值更新excel中的单元格 .

不,问题是我在第 If Trim(Name(3)) = Trim(Range("D4").Value) 行收到错误 Run-time error 9: Subscript out of range .

1 回答

  • 0

    然后将字符串中的thrid随机数与excel中的单元格值进行比较,以使用某些字符串值更新excel中的单元格 .

    你正在比较第四个随机数 . 你的'Name'元素是(0),(1),(2),(3),(4),...我想没有元素Name(3),因为你得到'超出范围'错误 .

相关问题