You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已有Python数组子集求和代码,如何用Excel VBA实现相同功能?

Excel VBA Implementation for Subset Sum Calculation

Your Python code uses a recursive approach to calculate all possible subset sums by either including or excluding each element in the array. Here's a direct VBA equivalent that follows the exact same logic:

' Recursive function to calculate and print all subset sums
Sub SubsetSums(arr As Variant, l As Integer, r As Integer, Optional currentSum As Double = 0)
    ' Base case: when we've processed all elements, print the current sum
    If l > r Then
        Debug.Print currentSum;
        Exit Sub
    End If
    
    ' Case 1: Include the current element (arr(l)) in the subset
    SubsetSums arr, l + 1, r, currentSum + arr(l)
    
    ' Case 2: Exclude the current element from the subset
    SubsetSums arr, l + 1, r, currentSum
End Sub

' Driver procedure to test the function
Sub TestSubsetSums()
    Dim arr As Variant
    arr = Array(5.76, 4.45, 3.2)
    
    ' Call the recursive function (VBA arrays are 0-indexed, matching your Python code)
    SubsetSums arr, 0, UBound(arr)
End Sub

How this works:

  • Recursive Logic: Just like your Python code, SubsetSums handles each element in two scenarios:
    1. Adding the current element's value to the running sum and moving to the next element.
    2. Skipping the current element and proceeding with the same running sum.
  • Base Case: When the left index (l) exceeds the right index (r), we've exhausted all elements for the current subset—so we print the accumulated sum to the Immediate Window (press Ctrl+G in the VBA Editor to view this output).
  • Driver Procedure: TestSubsetSums sets up your input array and triggers the recursive function. VBA uses 0-indexed arrays by default, so UBound(arr) gives us the last index, matching your Python code's n-1.

To run this:

  1. Open Excel, press Alt+F11 to launch the VBA Editor.
  2. Insert a new module (Right-click your workbook in the Project Explorer > Insert > Module).
  3. Paste the code above into the module.
  4. Run the TestSubsetSums procedure (press F5 while in the procedure, or use the Run menu).
  5. Check the Immediate Window for the full list of subset sums.

内容的提问来源于stack exchange,提问作者Dmitrij Holkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:46:41