Set Family Parameter Formula Issue

I’m working on copying formulas from one family to another and I’m having issues with the doc.FamilyManager.SetFormula() function.

I am using code by @Daniel_Woodcock1 that I found on the forum, and it somewhat works. The problem is that when I first run it, every parameter returns a “There is no valid family type.” error.

The weird thing is that if I were to create a new parameter and then rerun the script, almost all of the formulas will be created. There are still a few “Formula setting failed” errors (which I don’t understand either, any ideas would be appreciated), but overall, most of the formulas are successful.

Is there something I missing regarding making the parameters editable?

import clr

clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc =  DocumentManager.Instance.CurrentDBDocument
app = DocumentManager.Instance.CurrentUIApplication.Application

clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.ImportExtensions(Revit.GeometryConversion)

clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *

def tolist(obj1):
	if hasattr(obj1,"__iter__"): return obj1
	else: return [obj1]

pNames = tolist(IN[0])
fString = tolist(IN[1])

outList = []
errors = []
test = []
names = []

if doc.IsFamilyDocument:
	fMan = doc.FamilyManager	
	params = fMan.GetParameters()
	for pName,fStr in zip(pNames,fString):
		for p in params:
			pd = p.Definition
			pn = pd.Name
			names.append(pn)
			if pName == pn:
				if p.CanAssignFormula:
					TransactionManager.Instance.EnsureInTransaction(doc)
					if fMan.IsParameterLocked(p):
						fMan.SetParameterLocked(p,False)					
					try:
						fMan.SetFormula(p,fStr)
						test.append(pn)
						outList.append("Succeeded")
					except Exception, e:
						outList.append(e)
					TransactionManager.Instance.TransactionTaskDone()
				else:
					errors.append(pn)
	
	no =  set(names).difference(set(test))
OUT = outList, no
#For more information refer to RBG Wiki or email me (ctrl + click link): daniel.woodcock@robertbird.com