2

I am just wondering how i can skip over an error if the array is not full? For example, 1 loop goes over whether the array has a first and last name, if there is no last name i would like the script to continue.

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

If Name(1) is empty then how can the code continue?

1
  • FYI that intCount loop appears to be completely redundant; the second iteration would simply overwrite everything the first one did. Commented Feb 21, 2018 at 21:34

3 Answers 3

3

Since the two columns are consecutive, you can just paste the array in-place, using Range.Resize to dump the array across as many columns as needed - the only thing to watch for is if Name can contain more than a single space:

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
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to avoid using On Error Resume Next, you can try this:

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

which was originally posted here. Join essentially reverts to the FullName value but without the space. Alternatively, you could just use If InStr(1, FullName, " ", vbBinaryCompare) > 0 Then.

Comments

1

With some test values

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.