简体   繁体   中英

VBA's range causes “Run time error 9 Subscript out of range”

The following code fails whenever I go beyond certain number of columns eg if I was using this array: AD2:BM, everything works well and it bounds the letter with each other (its original purpose). However, whenever I try to go from AD2:KQ it fails by indicating

Run time error 9 Subscript out of range.

Can you please advise how to extend the ranges within this code (without generating error)? Regards West

Sub WL()
  Dim R As Long, C As Long, X As Long, Data As Variant
  Data = Range("AD2:BM" & Columns("AD:BM").Find("*", , xlValues, , xlRows, xlPrevious).Row)
  For R = 1 To UBound(Data, 1)
    X = -1
    For C = 1 To UBound(Data, 2)
      If Len(Data(R, C)) Then
        X = X + 1
        If X Then Data(R, C) = Data(R, C + 1) & Data(R, C)
      End If
    Next
  Next
  Range("AD2:BM2").Resize(UBound(Data)) = Data
End Sub

2. UPDATE:

All strings of W's & L's begin with one letter and end with one letter. Everything inbetween is perfect.

The question is: what can be done to double first far-right and first far-left values (that are singles)? Eg I have highlighted these event on the attached photo below [don't be fooled, every single string starts and ends with one letter - these two cases are simply visible in their entirety].

I need beginning and ending L or W to double, from W to WW and from L to LL. Wherease the W's & L's in between to remain the way they are, ie move from one period to the other and join other single letter [just like in the code below].

Thanks

在此输入图像描述

You are incrementing C to the UBound(Data, 2) but within that loop you expect to use Data(r, C + 1) which is outside the UBound.

Sub WL()
  Dim R As Long, C As Long, X As Long, Data As Variant
  Data = Range("AD2:BM" & Columns("AD:BM").Find("*", , xlValues, , xlRows, xlPrevious).Row)
  For R = 1 To UBound(Data, 1)
    X = -1
    For C = 1 To UBound(Data, 2) - 1   '<~~ FIX HERE!!
      If Len(Data(R, C)) Then
        X = X + 1
        If X Then Data(R, C) = Data(R, C + 1) & Data(R, C)    'Now C+1 doesn't error
      End If
    Next
  Next
  Range("AD2:BM2").Resize(UBound(Data)) = Data
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM