【问题标题】:Finding all available paths with a location connection list on Excel using VBA使用 VBA 在 Excel 上查找带有位置连接列表的所有可用路径
【发布时间】:2018-01-24 15:05:41
【问题描述】:

目前,我有一个连接位置列表,如下例所示:

A|B  
A|C  
B|C  
B|E  
C|D    
C|Z  

这意味着像 this

这样的网络

目标是,给定开始和结束位置,列出所有可能的路径。例如,给定 Start = A & End = Z,我们有:

A-C-Z  
A-B-C-Z

现在,我设置了以下代码:

Sub run_report()
    Set euh = Sheets("Input")
    'B5 and D5 are the two locations to be connected
    If euh.Range("B5").Value <> "" And euh.Range("D5").Value <> "" Then
        Call worm(euh.Range("B5").Value, euh.Range("D5").Value, 1,  euh.Range("B5").Value & "|")
        ' "Hops" is where the available paths will be displayed
        Sheets("Hops").Activate
    Else
        MsgBox "Both locations need to be selected!"
    End If
End Sub

'Starting/Current location, End/Goal location, current number of connections used so far, used nodes/locations in this path
Sub worm(vstart As String, vend As String, vlvl As Integer, used As String)
    ' "DB" is the connection list database
    Set sdb = Sheets("DB")
    Set sh = Sheets("Hops")
    Dim target As String
    Dim vline As Integer

    ' Iterates through all available connections looking for the next step
    For a = 1 To sdb.Range("A1").End(xlDown).Row
        If sdb.Range("A" & a).Value = vstart Or sdb.Range("B" & a).Value = vstart Then
            If sdb.Range("A" & a).Value = vstart Then
                target = sdb.Range("B" & a).Value
            Else
                target = sdb.Range("A" & a).Value
            End If


            If target = vend Then
                'Add successfull connection
                used = used & target
                vline = IIf(sh.Range("A2").Value <> "", sh.Range("A1").End(xlDown).Row + 1, 2)
                sh.Range("A" & vline).Value = vlvl
                sh.Range("C" & vline).Value = used
            'If the current node/location hasn't been used so far
            ElseIf InStr(used, target) = 0 Then
                used = used & target & "|"
                Call worm(target, vend, (vlvl + 1), used)
            End If
        End If
    Next a
End Sub

现在代码大部分按原样工作,但我认为问题在于,不是 sub [worm] 将参数作为临时参数传递给每个下一次递归,变量 vlvl 和 used 被视为全局,因此即使代码到达死胡同,用于到达那里的节点仍然被添加对于下一次迭代,因此前面的示例将打印为:

A-B-C-[D] (死胡同)-Z
[整个前一行] + A-C- [B-E](死角 1) -[D](死角 2) - Z

关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: excel vba recursion path-finding


    【解决方案1】:

    used 并不是被视为全局变量,而是您在调用递归函数之前对其进行了更改。尝试删除used = used &amp; target &amp; "|"并将下一行更改为Call worm(target, vend, (vlvl + 1), used &amp; target &amp; "|")

    【讨论】:

    • 我也试过了,但这会使 Excel 崩溃/无响应。我尝试将used 参数设为ByVal,但这会导致同样的问题。
    • 显然你是对的,唯一的问题是我正在处理的数据库的大小。我尝试了示例一,效果很好。没有找到一种方法来使这个工作与 120 个连接列表一起工作!
    猜你喜欢
    • 2017-06-26
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    相关资源
    最近更新 更多