简体   繁体   English

遍历Excel中的已定义列表

[英]Iterate over defined lists in excel

I have an excel spreadsheet, with two defined lists. 我有一个Excel电子表格,其中包含两个已定义的列表。 Call them colours{red, green, blue} and types{1, 2} 称其为颜色{红色,绿色,蓝色}和类型{1、2}

I have a function to calculate for each object, so finally, I have a table that looks like 我有一个为每个对象计算的函数,所以最后,我有一个表,看起来像

colour type result

red 1 100 红色1100

red 2 200 红色2200

green 1 150 绿色1150

green 2 250 绿色2250

blue 1 155 蓝色1155

blue 2 255 蓝色2255

But obviously I wrote that by hand. 但是显然我是手工写的。 Without using a VB script, is there any way I can get excel to fill in the colour and type cells to enumerate the whole set? 如果不使用VB脚本,有什么办法可以使Excel填写颜色并键入单元格以枚举整个集合?

Thanks 谢谢

Here's one VBA approach - you can pass in as many lists (by range) as you like and it will create all the combinations and copy them to where you specify. 这是一种VBA方法-您可以根据需要传入任意数量的列表(按范围),它将创建所有组合并将其复制到您指定的位置。

Sub tester()

    'First range is where to place the results, next ranges
    '  are the lists to be combined
    SqlPermutate Sheet1.Range("E1"), Sheet1.Range("A1:A20"), _
                 Sheet1.Range("B1:B5"), Sheet1.Range("C1:C10")

End Sub


Sub SqlPermutate(rngDestination As Range, ParamArray ranges() As Variant)

    Dim oConn As Object, oRS As Object
    Dim sPath, i As Long, srcWb As Workbook
    Dim sSQL As String, flds As String, tbls As String

    'check source ranges are in a saved workbook...
    Set srcWb = ranges(0).Parent.Parent
    If srcWb.Path <> "" Then
      sPath = srcWb.FullName
    Else
      MsgBox "Workbook being queried must be saved first..."
      Exit Sub
    End If

    For i = LBound(ranges) To UBound(ranges)
        flds = flds & IIf(Len(flds) > 0, ",", "") & Chr(65 + i) & ".*"
        tbls = tbls & IIf(Len(tbls) > 0, ",", "") & _
                RngNm(ranges(i)) & " " & Chr(65 + i)
    Next i

    sSQL = "select " & flds & " from " & tbls
    Debug.Print sSQL

    Set oConn = CreateObject("adodb.connection")
    Set oRS = CreateObject("ADODB.Recordset")

    oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sPath & "';" & _
                 "Extended Properties='Excel 12.0;HDR=no;IMEX=1';"

    oRS.Open sSQL, oConn

    If Not oRS.EOF Then
        rngDestination.CopyFromRecordset oRS
    Else
        MsgBox "No records found"
    End If

    oRS.Close
    oConn.Close

End Sub

Function RngNm(r) As String
    RngNm = "[" & r.Parent.Name & "$" & _
                r.Address(False, False) & "]"
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM