根据行索引转换Excel列表

时间:2015-02-20 22:27:28

标签: arrays excel vba excel-vba excel-formula

我尝试按如下方式转换Excel VBA中的列表:

我的原始列表中有一个灰色的。它显示了一个序列。 我想根据每个数字位置在右边生成列表。

sample list and output

例如:
左侧列表中的3 ,因此2位于右侧列表中的第三个位置;
左侧列表中的6 第四,因此4位于右侧列表的第六位置...

我尝试使用' For'在VBA中循环,但它有点长而复杂,有没有办法在VBA中使用数组呢?

3 个答案:

答案 0 :(得分:3)

公式可以轻松实现这一目标。假设数据在A1:A8中,在B1中并向下复制:

=MATCH(ROW(),A$1:A$8,0)

答案 1 :(得分:1)

这将起作用,只需根据需要设置第一个,最后一个和范围。

Private Sub cbSort_Click()

Dim wArray As Variant, dArray As Variant
Dim first As Integer, last As Integer
Dim i As Integer, j As Integer

first = 1
last = 8

Set wArray = Range("A" & first & ":A" & last)
ReDim dArray(1 To last - first + 1, 1 To 1)

j = 1
For i = first To last
  dArray(wArray(i, 1), 1) = j
  j = j + 1
Next i

Range("B" & first & ":B" & last) = dArray

End Sub

答案 2 :(得分:1)

Option Explicit

Sub Main()
    Dim source As Range
    On Error GoTo ErrTransformIt
    Set source = Application.InputBox(prompt:="Source", Type:=8)
    TransformIt source
    Exit Sub
ErrTransformIt:
    MsgBox Err.Description
End Sub

Private Sub TransformIt(ByVal source As Range)
    Dim target As Range
    Dim c As Range
    Dim i As Integer
    Dim firstRow As Long

    firstRow = source(1).Row
    i = 1

    For Each c In source.Cells
        Set target = ActiveSheet.Cells(firstRow + c.Value - 1, c.Column + 1)
        If target.Value <> "" Then
            MsgBox "Target is already used by [" & target.Value & "]", vbExclamation
            Exit Sub
        End If
        target.Value = i
        i = i + 1
    Next c
End Sub