简体   繁体   English

VBA的范围导致“运行时错误9下标超出范围”

[英]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). 每当我超出一定数量的列时,以下代码都会失败,例如,如果我使用的是这个数组:AD2:BM,一切正常并且它将字母相互绑定(其原始用途)。 However, whenever I try to go from AD2:KQ it fails by indicating 但是,每当我尝试从AD2:KQ失败时,它都会失败

Run time error 9 Subscript out of range. 运行时错误9下标超出范围。

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: 2.更新:

All strings of W's & L's begin with one letter and end with one letter. W&L的所有字符串都以一个字母开头,以一个字母结尾。 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. 我需要开始和结束L或W加倍,从W到WW,从L到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]. 其中W和L在两者之间保持原样,即从一个时期转移到另一个时期并加入其他单个字母[就像在下面的代码中一样]。

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. 您正在将C递增到UBound(数据,2),但在该循环内,您希望使用UBound之外的数据(r,C + 1)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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