已有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,
SubsetSumshandles each element in two scenarios:- Adding the current element's value to the running sum and moving to the next element.
- 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 (pressCtrl+Gin the VBA Editor to view this output). - Driver Procedure:
TestSubsetSumssets up your input array and triggers the recursive function. VBA uses 0-indexed arrays by default, soUBound(arr)gives us the last index, matching your Python code'sn-1.
To run this:
- Open Excel, press
Alt+F11to launch the VBA Editor. - Insert a new module (Right-click your workbook in the Project Explorer > Insert > Module).
- Paste the code above into the module.
- Run the
TestSubsetSumsprocedure (pressF5while in the procedure, or use the Run menu). - Check the Immediate Window for the full list of subset sums.
内容的提问来源于stack exchange,提问作者Dmitrij Holkin
相关产品推荐
相关产品推荐

