开发者

Recovering and sorting data from a sparse worksheet in Excel VBA

开发者 https://www.devze.com 2023-02-18 21:18 出处:网络
I have several sparsely populated tables in an Excel workbook from which I need to recover and sort the values for specific keys. The lookups will be triggered by Events.

I have several sparsely populated tables in an Excel workbook from which I need to recover and sort the values for specific keys. The lookups will be triggered by Events.

I could do this using Loops and an array but having been warned off Loops in VBA I am wondering if there is a more elegant method perhaps using an inbuilt excel function.

Speed is important.

UID| UK | FR | DE | FI | LUX | .....
 1 |  0 |  0 |0.03| 0.1|   0 | .....
 2 |  0 |  0 |  0 |  0 | 0.5 | .....
 3 |0.01|  0 |  0 |  0 | 0.09| .....
 4 |  0 |  0 |  0 | 0.2|   0 | .....
 5 |0.31|0.07|  0 |  0 |   0 | .....
 .    .    .    .    .     .
 .    .    .    .    .     .
 .    .    .    .    .     .
 .    .    .    .    .     .

So in this sample table I would want to return the geograp开发者_开发百科hic distribution of each Unique ID and sort it, omitting any region with 0 weighting.

The table sheet has several thousand UIDs and several thousand regions.


It's still not quite clear to me what you're trying to accomplish, but I will say this much: there is no built-in Excel function to do it -- or at least not as well as if you code it yourself.

Try this:

Dim rngData As Range
Dim varDummy As Variant
Dim iUID As Long, iRegion As Long

Set rngData = Range("A2:Z50") ' or wherever your data is

varDummy = rngData ' Reads in whole range at once into array. (Must be Variant.)
                   ' Much quicker than accessing one cell at a time.

' Go nuts with loops here.
For iUID = LBound(varDummy,1) To UBound(varDummy,1)
    For iRegion = LBound(varDummy,2) To UBound(varDummy,2)

        If varDummy(iUID,iRegion) = 0 Then
            ' Nothing here, ignore this cell.
            ' Do nothing.
        Else
            ' Do your thang
            ' ... code for whatever it is you want to do goes here.
        End If

    Next iRegion
Next iUID
0

精彩评论

暂无评论...
验证码 换一张
取 消