Results 1 to 7 of 7

For Loop within a Function

Threaded View

  1. #1
    Registered User
    Join Date
    02-02-2014
    Location
    Scotland
    MS-Off Ver
    Excel 2010
    Posts
    4

    For Loop within a Function

    I am trying to write a basic function in the VBA editor in excel. It must have a loop inside it which creates values and then sums those values once the loop has completed. To understand what I am trying to do, I wrote a code in Matlab so you can see what I am trying to do. I have included comments and my attempt at the VBA code so far. Thanks in advance!

    MATLAB CODE:


    function binomial (k,n,p)
    
    binomial=zeros(1,(n-k+1)); %allocate memory space for vector
    for i=1:(n-k+1) %loop starts at 1, (n-k+1) ensures the loop is the correct length
        binomial(i)=(factorial(n))/(factorial(k+i-1)*factorial(n-(k+i-1)))*p^(k+i-1)*(1-p)^(n-(k+i-1)); %(k+i-1) is used to ensure the correct position of k and allow the matrix created to start adding in position (1,1)
    end
    
    sum(binomial) %sums all the odds of all posibilities of success
    
    end


    EXCEL CODE SO FAR:

    Function binomial(k, n, p)
        
        For i = 1 To (n - k + 1)    'loop starts at 1, (n-k+1) ensures the loop is the correct length
            binomial(i) = (WorksheetFunction.Fact(n)) / (WorksheetFunction.Fact(k + i - 1) * WorksheetFunction.Fact(n - (k + i - 1))) * p ^ (k + i - 1) * (1 - p) ^ (n - (k + i - 1)) '(k+i-1) is used to ensure the correct position of k and allow the matrix created to start adding in position (1,1)
        Next i
    
    End Function


    Basically I don't know how to create an array in VBA, populate with it the values from the loop and then sum the array like I did in MATLAB.
    Last edited by alansidman; 02-02-2014 at 10:52 AM. Reason: code tags added

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Copy dynamically changing column and Paste using VBA Loop (Loop within Loop)
    By nixon72 in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 02-12-2013, 12:46 PM
  2. [SOLVED] Help with Loop Function
    By Clue_Less in forum Excel Programming / VBA / Macros
    Replies: 12
    Last Post: 06-14-2012, 04:09 PM
  3. Loop a function
    By fcomino in forum Excel Programming / VBA / Macros
    Replies: 11
    Last Post: 05-20-2010, 12:57 PM
  4. loop does not function as I wish
    By dschmitt in forum Excel General
    Replies: 5
    Last Post: 03-03-2010, 12:22 AM
  5. Loop Function unable to loop
    By Junior728 in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 07-28-2005, 06:05 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1