excel - Clear Constants in a range without clearing references and formulas -
i trying clear number constants in range of cells without clearing formulas or cell references. clearing constants cells without formulas or cell references simple having trouble doing when present. below code have far.
range("b2:b11").select selection.specialcells(xlcelltypeconstants, 1).select selection.clearcontents
in range cells b5 , b7 have formulas cell references follows:
b5: =(g83*h1)+1181.05
b7: =e33+1292.76
the cell references @ times reference cells on other sheets in same workbook. need clear constants these formulas while leaving references intact.
this remove constants formulas in current workbook based on 2 patterns:
"=formula-[space]-
plussign
-[space]-constant"
(space optional)=(g83*h1)+1181.05 or =(g83*h1) +1181.05 or =(g83*h1)+ 1181.05
becomes=(g83*h1)
=e33+1292.76 or =e33 +1292.76 or =e33+ 1292.76 or =e33 + 1292.76
becomes=e33
"=formula-[space]-
minussign
-[space]-constant"
(space optional)
public sub clearconstantsfromworkbookformulas() const patterns string = "~+*|~+ *|~ +*| ~+ *|~-*|~- *|~ -*|~ - *" dim pat variant each pat in split(patterns, "|") cells.replace what:=pat, _ replacement:=vbnullstring, _ lookat:=xlpart, _ searchorder:=xlbyrows, _ matchcase:=false next end sub
.
this more generic option using regex pattern matching , arrays:
public sub testclear() dim ws worksheet each ws in application.activeworkbook.worksheets removeconstantsfromformulas ws.range("b2:b11"), getregex next end sub public sub removeconstantsfromformulas(byref rng range, byref regex object) dim v variant, r long, c long, lr long, lc long lr = rng.rows.count lc = rng.columns.count if lr > 0 , lc > 0 v = rng.formula r = 1 lr c = 1 lc if left(v(r, c), 1) = "=" if regex.test(v(r, c)) v(r, c) = regex.replace(v(r, c), vbnullstring) end if next next rng.formula = v end if end sub private function getregex() object set getregex = createobject("vbscript.regexp") getregex.pattern = "[^a-za-z][0-9]+(\.?[0-9]+)" getregex.global = true getregex.ignorecase = true end function
regex pattern: 1 or more digits, digit group not preceded letter, or without fraction part
Comments
Post a Comment