Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel - VBA: does Worksheet.Range.Delete have a columns number limitation?

Tags:

excel

vba

I have an issue with a simple line that deletes some targeted columns. I used such a line plenty of times but it is the first time that I got an error on it. The fact is it's a lot of columns, too much it seems, because when I delete some of them in the quotes (approximately 10), I don't have an error anymore. So does it mean that VBA have a limit of the number of columns in a range?

MyWorksheet.Range("Q:Q,R:R,S:S,T:T,U:U,V:V,W:W,X:X,Y:Y,Z:Z,AA:AA,AB:AB,AC:AC,AD:AD,AE:AE,AF:AF,AG:AG,AH:AH,AJ:AJ,AL:AL,AN:AN,AP:AP,AR:AR,AT:AT,AV:AV,AX:AX,AZ:AZ,BB:BB,BD:BD,BH:BH,BJ:BJ,BL:BL,BN:BN,BP:BP,BR:BR,BT:BT,BV:BV,BX:BX,BZ:BZ,CB:CB,CF:CF,CH:CH,CJ:CJ,CN:CN,CP:CP,CR:CR,CT:CT").Delete Shift:=xlToLeft 

Those columns come from a list of string, so I am aware that I could do a For loop and delete one by one.

I'm new to Stack Overflow and not an English native so sorry if I did any mistakes.

EDIT :

Originally, I use a dictionary to store some specific columns, then I aggregate the dictionary items with some comas and put the variable in my range.

For i = 1 To ColToDeleteArray.Count
    If ColToDeleteArray.Exists(i) Then
        ColToDeleteString = ColToDeleteString & ColToDeleteArray(i) & ":" & ColToDeleteArray(i) & ","
    End If
Next i

ColToDeleteString = Left(ColToDeleteString, Len(ColToDeleteString) - 1)
MyWorksheet.Range(ColToDeleteString).Delete Shift:=xlToLeft
like image 259
Chris Avatar asked Jun 07 '18 14:06

Chris


1 Answers

Consider:

Sub hfsjdfh()
    Dim s As String, r As Range
    s = "Q:Q,R:R,S:S,T:T,U:U,V:V,W:W,X:X,Y:Y,Z:Z,AA:AA,AB:AB,AC:AC,AD:AD,AE:AE,AF:AF,AG:AG,AH:AH,AJ:AJ,AL:AL,AN:AN,AP:AP,AR:AR,AT:AT,AV:AV,AX:AX,AZ:AZ,BB:BB,BD:BD,BH:BH,BJ:BJ,BL:BL,BN:BN,BP:BP,BR:BR,BT:BT,BV:BV,BX:BX,BZ:BZ,CB:CB,CF:CF,CH:CH,CJ:CJ,CN:CN,CP:CP,CR:CR,CT:CT"
    arr = Split(s, ",")
    For Each a In arr
        If r Is Nothing Then
            Set r = Range(a)
        Else
            Set r = Union(r, Range(a))
        End If
    Next a
    MsgBox r.Address(0, 0)
End Sub

enter image description here

  • So even if the string is too long for the Range object to handle, it can still be used via Union().
  • Once the range has been created, its address is somewhat compact compared to the original string.
like image 190
Gary's Student Avatar answered Nov 23 '22 23:11

Gary's Student