如果数组为空,则VBA继续

时间:2018-02-21 20:59:34

标签: arrays vba loops



我对VBA非常陌生。我目前正在创建一个脚本,这将节省我很多时间手指交叉

我只是想知道如果数组不满,我怎么能跳过错误?例如,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)为空,那么代码如何继续?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 :(得分:1)

如果您想避免使用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