【问题标题】:VBA Continue If Array Empty如果数组为空,VBA 继续
【发布时间】:2018-08-01 14:12:14
【问题描述】:

我只是想知道如果数组未满,如何跳过错误?例如,1 循环检查数组是否有名字和姓氏,如果没有姓氏,我希望脚本继续。

FullName = ActiveSheet.Cells(37, ii).Value
Name = Split(FullName, " ")

For intCount = LBound(Name) To UBound(Name)
  sData.Range("C" & iii).Value = Name(0)
  sData.Range("D" & iii).Value = Name(1)
Next

如果Name(1) 为空,那么代码如何继续?

【问题讨论】:

  • 仅供参考,intCount 循环似乎是完全多余的;第二次迭代只会覆盖第一次所做的一切。

标签: arrays vba loops


【解决方案1】:

带有一些测试值

Option Explicit

Sub test()

Dim ii As Long
Dim iii As Long

ii = 2
iii = 3

Dim FullName As String
Dim Name() As String

With ActiveSheet

    FullName = .Cells(37, ii).Value

    If InStrRev(FullName, " ", -1) > 0 Then   'space present

        Name = Split(FullName, " ")

        If UBound(Name) > 1 Then Exit Sub 'there was more than one space present. Handling this was not specified so exit sub.

        .Range("C" & iii).Value = Name(0)
        .Range("D" & iii).Value = Name(1)

    Else

         .Range("C" & iii).Value = FullName
         .Range("D" & iii).Value = vbNullString

    End If

End With

End Sub

【讨论】:

    【解决方案2】:

    如果你想避免使用On Error Resume Next,你可以试试这个:

    FullName = ActiveSheet.Cells(37, ii).Value
    Name = Split(FullName, " ")
    
    If Len(Join(Name)) > 0 Then
        sData.Range("C" & iii).Value = Name(0)
        sData.Range("D" & iii).Value = Name(1)
    End If
    

    最初发布于hereJoin 基本上恢复为 FullName 值,但没有空格。或者,您可以只使用If InStr(1, FullName, " ", vbBinaryCompare) > 0 Then

    【讨论】:

      【解决方案3】:

      由于两列是连续的,您可以直接粘贴数组,使用 Range.Resize 将数组转储到所需的任意多列 - 唯一需要注意的是 Name 是否可以包含超过一个空格:

      FullName = ActiveSheet.Cells(37, ii).Value
      Name = Split(FullName, " ")
      If UBound(Name) <= 1 Then
          sData.Range("C" & iii).Resize(, UBound(Name) + 1).Value = Name
      Else
          'there was more than one space...
      End If
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-17
        • 2016-11-16
        • 2018-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多