You could use a query like:
let
fnSourceStock = (ItemData, Item) =>
let
#"Filtered ItemData" = Table.SelectRows(ItemData, each ([Item number] = Item) and ([Branch] = "A")),
#"Source Stock" = List.Sum(#"Filtered ItemData"[Current stock])
in
#"Source Stock",
fnPriorDemand = (ItemData, Item, Branch) =>
let
#"Filtered ItemData" = Table.SelectRows(ItemData, each ([Item number] = Item) and ([Branch] <> "A") and ([Branch] < Branch)),
#"Prior Demand" = List.Sum(#"Filtered ItemData"[To be transfer from Branch A])
in
#"Prior Demand",
Source = Excel.CurrentWorkbook(){[Name="ItemData"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Item number", type text}, {"Branch", type text}, {"Current stock", Int64.Type}, {"To be transfer from Branch A", Int64.Type}}),
#"Added Source Stock" = Table.AddColumn(#"Changed Type", "Source Stock", each fnSourceStock(#"Changed Type", [Item number]), Int64.Type),
#"Added Prior Demand" = Table.AddColumn(#"Added Source Stock", "Prior Demand", each fnPriorDemand(#"Changed Type", [Item number], [Branch]), Int64.Type),
#"Added Available Qty" = Table.AddColumn(#"Added Prior Demand", "Available To Transfer", each List.Max ({0, [Source Stock] - [Prior Demand]}), Int64.Type),
#"Added Transfer Qty" = Table.AddColumn(#"Added Available Qty", "Transfer From Source", each List.Min({[Available To Transfer], [To be transfer from Branch A]}), Int64.Type),
#"Removed Columns" = Table.RemoveColumns(#"Added Transfer Qty",{"Source Stock", "Prior Demand", "Available To Transfer"})
in
#"Removed Columns"
However - I'd use PowerPivot instead.
First of all, I'd create a Branches table - as I'm sure your branch names won't always be in conveniently alphabetical order - so this table establishes the source branch, and the transfer priority of the remainder.
tables.png
I'd load both tables to the data model (using Power Query) and create a relationship on [Branch]:
relationship.png
Now you can add a calculated column to table ItemData:
TransferFromSource:=
VAR SourceStock =
CALCULATE (
SUM ( ItemData[Current stock] ),
ALLEXCEPT ( ItemData, ItemData[Item number] ),
Branches[Priority] = "Source"
)
VAR CurrentPriority =
RELATED ( Branches[Priority] )
VAR PriorDemand =
CALCULATE (
SUM ( ItemData[To be transfer from Branch A] ),
ALLEXCEPT ( ItemData, ItemData[Item number] ),
FILTER (
ALL ( Branches[Priority] ),
Branches[Priority] <> "Source" && Branches[Priority] < CurrentPriority
)
)
VAR AvailableToTransfer =
MAX ( 0, SourceStock - PriorDemand )
RETURN
MIN ( AvailableToTransfer, ItemData[To be transfer from Branch A] )
Gives your expected results:
pp_output.png
Bookmarks