如果单元格中的值符合条件,则从特定列中反向选择数据

时间:2018-07-11 19:24:31

标签: excel vba excel-vba excel-2010

我有一个表单,用户可以在其中输入项目名称和交易类型。

我编写了一个宏,该宏根据用户输入的项目名称从表中返回数据的选择,并且效果很好。

现在,我需要添加一个函数,如果用户输入特定的交易类型,则该函数可以反转相同列表的顺序,它可以反转相同数据列表的顺序。

例如,如果类型A返回:

鲍勃

杰里

安德鲁

杰夫

然后类型B将颠倒该顺序并返回:

杰夫

安德鲁

杰里

鲍勃

我为第一部分编写的VBA根据项目名称返回列表为:

Sub finddata()

Dim projectName As String
Dim transactionType As String
Dim finalRow As Integer
Dim i As Integer

Sheets("Template_Test").Range("G10:I38").ClearContents

projectName = Sheets("Template_Test").Range("E10").Value
finalRow = Sheets("Project_Structure").Range("A20000").End(xlUp).Row
transactionType = Sheets("Template_Test").Range("E14").Value

For i = 2 To finalRow
    Sheets("Project_Structure").Activate
    If Cells(i, 1) = projectName Then
        Sheets("Project_Structure").Range(Cells(i, 2), Cells(i, 4)).Copy
    Sheets("Template_Test").Activate
        Sheets("Template_Test").Range("G100").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
        End If
Next i

Sheets("Template_Test").Range("E10").Select

End Sub

我可以使用内置的vba函数strReverse和特定范围来使选择反向,但是我的数据不是一致的单元格长度-有时是6个名称,有时是15个-我无法弄清楚如何调整它需要反转的长度而又不包括该范围以下的空白单元格。

1 个答案:

答案 0 :(得分:0)

这是使用.Reverse对象的ArrayList方法的方法

Option Explicit
Public Sub ReverseAList()
    Dim ws As Worksheet, arr(), i As Long, aList As Object, lastRow As Long
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set aList = CreateObject("System.Collections.ArrayList")
    With ws
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'whichever column is required to determine last row. Assumes there are headers in row1
        If lastRow = 2 Then arr(0) = .Range("A2").Value
        arr = .Range("A2:A" & lastRow).Value
        For i = LBound(arr, 1) To UBound(arr, 1)
            aList.Add arr(i, 1)
        Next i

        aList.Reverse

        For i = 0 To aList.Count - 1
            arr(i + 1, 1) = aList(i)
        Next

        .Cells(2, 2).Resize(aList.Count, 1) = arr
    End With
End Sub

数据和输出

Data and output


同一件事由Ryan Wells重新编写了一个子函数:

Public Sub ReverseAList2()
    Dim ws As Worksheet, arr(), i As Long, aList As Object, lastRow As Long
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    With ws
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'whichever column is required to determine last row. Assumes there are headers in row1
        If lastRow = 2 Then arr(0) = .Range("A2").Value
        arr = .Range("A2:A" & lastRow).Value
        .Cells(2, 2).Resize(UBound(arr), 1) = ReverseArray(arr)
    End With
End Sub

Public Function ReverseArray(vArray As Variant) As Variant
    Dim vTemp As Variant, i As Long, iUpper As Long, iMidPt As Long
    iUpper = UBound(vArray, 1)
    iMidPt = (UBound(vArray, 1) - LBound(vArray, 1)) \ 2 + LBound(vArray)
    For i = LBound(vArray) To iMidPt
        vTemp = vArray(iUpper, 1)
        vArray(iUpper, 1) = vArray(i, 1)
        vArray(i, 1) = vTemp
        iUpper = iUpper - 1
    Next i
    ReverseArray = vArray
End Function