Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - Google Scripts / Sheets Add prefix to data once it has been entered into the cell

Objectives

  1. Add a Prefix of CSC1[Leading Zeros] to a number such as 1291 or 12922 or 129223 this should apply to the whole column (Column F)
  2. Ensure total string length is = 15 using padding of zeros so the cell value would be CSC100000001291
  3. The user would only enter 1291 but I plan to make the script overwrite this to make the the cell value CSC100000001291

Can be done using a formula but across two columns but would prefer to use one column as it look tidier.

e.g [User Input] = [Final Cell Value]

 - 1291 = CSC100000001291
 - 12922 = CSC100000012922

Currently trying to work this one out

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following:

  • An onEdit trigger to check when someone has updated a cell
  • padStart() to add the leading zeros
  • replace() the first 4 zeros with "CSC1" (since only the first occurrence will be replaced if passing a string instead of regular expression)
  • setValue() to update the edited cell
function onEdit(e) {
  if (e.range.columnStart == 1) { // Column A
    const padded = e.value.padStart(15, 0);
    e.range.setValue(padded.replace('0000', 'CSC1'));
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...