【问题标题】:Type Mismatch error stepping through an array类型不匹配错误单步执行数组
【发布时间】:2020-01-16 14:04:56
【问题描述】:

我有以下代码。我将“d”列中的单元格值作为字符串(一周中的几天的列表,可以是一天或所有 7 天)传递给这个函数。我还使用该函数来填充整数数组。我在指示的行出现类型不匹配,我不知道为什么。特别是因为我在填充它并逐步通过它之前对数组进行了调暗。我将不胜感激任何帮助/解释。显式选项已打开。

Public i as Integer

Public Function ParseColumnD(cellvalue as String) as String

Dim BREdaysString() as String
Dim daysAsInt() As Integer

BREdaysString() = Split(cellvalue, ", ")

For Each i in BREdaysString()
    If BREdaysString(i) = "Monday" Then           '<-----Type Mismatch error here.
        daysAsInt(i) = 4
    ElseIf BREdaysString(i) = "Tuesday" Then
        daysAsInt(i) = 5
    ElseIf BREdaysString(i) = "Wednesday" Then
        daysAsInt(i) = 6
    ElseIf BREdaysString(i) = "Thursday" Then
        daysAsInt(i) = 7
    ElseIf BREdaysString(i) = "Friday" Then
        daysAsInt(i) = 8
    ElseIf BREdaysString(i) = "Saturday" Then
        daysAsInt(i) = 9
    ElseIf BREdaysString(i) = "Sunday" Then
        daysAsInt(i) = 10
    End If
Next

'to check to make sure the conversion from days of the week to integers is correct 
'I take the int array and put it as the function's string, return it and put in another cell.

For Each i in daysAsInt()
   If i = 1 Then
      ParseColumnD = daysAsInt(i)
   ElseIf i > 1 Then
      ParseColumnD = ParseColumnD & ", " & daysAsInt(i)
   End If
Next
End Funciton

在常规模块中我使用这样的函数...

Sub MySub()

Dim BREitems as Range
Dim lastrow as Long

lastrow = Cells(Rows.count, "a").End(xlUp).Row
Set BREitems = Range("a5:a" & lastrow)

For Each i in BREitems
    Cells(i.Row, "g").value = ParseColumnD(Cells(i.row, "d"))
Next
End Sub




【问题讨论】:

    标签: arrays excel vba


    【解决方案1】:

    您希望在此处使用LBoundUbound 而不是For Each 循环来迭代数组。

    For i = LBound(BREdaysString) to Ubound(BREdaysString)
    

    如果您执行以下操作,For Each 循环将起作用:

    For Each i in BREdaysString()
         If i = "Monday" Then 
    

    显然使用比iDimming 更好的变量名作为String,因为这非常令人困惑。但是,如果您使用的是For Each 循环,则不能将i 用作索引。这就像尝试做If BREdaysString("Monday") = "Monday" Then

    我也看不出i 成为Public 的意义。还有just use Long instead of Integer

    【讨论】:

    • 改变这个循环效果很好!谢谢你。 i 是一个公共变量,因为我在整个项目的循环中都使用它。我不想在每个子/函数中声明它。我只在此处包含它,因为我说选项显式已打开,并且我想确保示例代码声明了所有变量。
    • 拥有Public 是不好的做法,IMO。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2013-03-14
    • 2017-09-05
    • 2023-03-06
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多