Excel reorders columns using list

I want to reorder some columns in excel using a list of values ​​that are in M1-M10 and which have a heading name and the order in which they should be ordered.

I have this script that works if I use:

v = Array("First Name", "Middle Name", "Last Name", "Date of Birth", "Phone Number", "Address", "City", "State", "Postal (ZIP) Code", "Country")

However, when I changed to

v = Range("m1:m10").Value

It does not work, indicating the following message:

Subcategory out of range.

Here is the whole code:

Sub Reorganize_columns()
' Reorganize Columns Macro
'
' Developer: If you want to know, please contact Winko Erades van den Berg
' E-mail : winko at winko-erades.nl
' Developed: 11-11-2013
' Modified: 11-11-2013
' Version: 1.0
''v = Array("First Name", "Middle Name", "Last Name", "Date of Birth", "Phone Number", "Address", "City", "State", "Postal (ZIP) Code", "Country")
' Description: Reorganize columns in Excel based on column header

Dim v As Variant, x As Variant, findfield As Variant
Dim oCell As Range
Dim iNum As Long


v = Range("m1:m10").Value
For x = LBound(v) To UBound(v)
findfield = v(x)
iNum = iNum + 1
Set oCell = ActiveSheet.Rows(1).Find(What:=findfield, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

If Not oCell.Column = iNum Then
Columns(oCell.Column).Cut
Columns(iNum).Insert Shift:=xlToRight
End If
Next x
End Sub
+4
source share
3 answers

You need to findfield = v(x,1), since an array from the range will be automatically 2D.

+2
source

I would rather use a collection instead of an array, but if you want, you can assign values ​​like this:

Dim i As Long

ReDim v(0 To 0)
For i = 0 To 9
    ReDim Preserve v(0 To i)
    v(i) = Range("m1").Offset(i)
Next i
0
source

ARRAY(), 0. , v, :

v = Array("First Name", "Middle Name", "Last Name", "Date of Birth", "Phone Number", "Address", "City", "State", "Postal (ZIP) Code", "Country")

5 :

Dim v(0 To 9) As String, i As Long

    arr = Range("M1:M10")
    For i = 0 To 9
        v(i) = arr(i + 1, 1)
    Next i
0
source

Source: https://habr.com/ru/post/1690694/


All Articles