• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Handling an empty array

PipBoy808

Member
Hello,
I'm using the split function to isolate the second portion of a string. Depending on what that second portion is, a particular heading is added to a worksheet. However, occasionally this second portion might be blank. This returns the following error:
"Run time error (9): Subscript out of range"
My code is something like this:
Code:
Dim k as variant
Dim POnumber as string
POnumber="12345-Germany"
k=Split(POnumber, "-")
If k(2)="Germany" then 'if k is nothing, the code returns an error here
Cells(10,3).value = "GermanyHeader"
Elseif k(2)="France" then
Cells(10,3).value= "FranceHeader"
end if
Can anyone advise me as to handle a potentially blank value for k?
Thanks!
 
@PipBoy808,

Please try the changes below.

Code:
Dim k As Variant
Dim POnumber As String
POnumber = "12345Germany"
k = Split(POnumber, "-")
If UBound(k) = 2 Then
    If k(2) = "Germany" Then 'if k is nothing, the code returns an error here
        Cells(10, 3).Value = "GermanyHeader"
        ElseIf k(2) = "France" Then
        Cells(10, 3).Value = "FranceHeader"
    End If
End If

Hope that helps.

Regards,
Ken
 
Back
Top