समझिए
1. आपका पहला custom function
Apps Script एडिटर में:
/**
* Adds GST to an amount.
*
* @param {number} amount The amount before tax.
* @param {number} rate GST rate in percent, e.g. 18.
* @return The amount including GST.
* @customfunction
*/
function WITHGST(amount, rate) {
if (amount === '' || amount === null) return '';
return Number(amount) * (1 + Number(rate) / 100);
}
सेव करें। शीट में =WITHGST(1000, 18) टाइप करें → 1180।
@customfunction वाला कमेंट ब्लॉक (JSDoc) फ़ंक्शन को आपके विवरण और आर्ग्युमेंट की मदद के साथ ऑटोकम्प्लीट में दिखाता है।
2. नाम रखना
- शीट में फ़ंक्शन के नाम केस-सेंसिटिव नहीं होते, पर कैपिटल अक्षर उन्हें बिल्ट-इन फ़ंक्शन जैसा दिखाते हैं।
- नाम अंडरस्कोर पर ख़त्म नहीं हो सकते (वे private होते हैं) और बिल्ट-इन फ़ंक्शन से टकराने नहीं चाहिए।
3. रेंज के साथ काम
रेंज देने पर फ़ंक्शन को 2D array मिलता है। 2D array लौटाएँ और नतीजे नीचे फैल जाते हैं:
/**
* Adds GST to every value in a range.
* @param {number[][]} amounts Range of amounts.
* @param {number} rate GST percent.
* @customfunction
*/
function WITHGST_RANGE(amounts, rate) {
if (!Array.isArray(amounts)) return WITHGST(amounts, rate);
return amounts.map(row => row.map(v => (v === '' ? '' : Number(v) * (1 + Number(rate) / 100))));
}
=WITHGST_RANGE(B2:B100, 18) — एक फ़ॉर्मूला पूरा कॉलम भर देता है। 100 अलग-अलग कॉल से कहीं तेज़।
4. एक काम का उदाहरण: भारतीय अंक समूह (लाख/करोड़)
/**
* Formats a number with Indian digit grouping, e.g. 1234567 -> 12,34,567.
* @param {number} n The number.
* @customfunction
*/
function INRFORMAT(n) {
if (n === '' || isNaN(n)) return '';
return Number(n).toLocaleString('en-IN', { maximumFractionDigits: 2 });
}
=INRFORMAT(1234567) → 12,34,567। (नतीजा टेक्स्ट है, दिखाने या लेबल के लिए।)
5. Custom functions को मानने वाले नियम
- सिर्फ़ वैल्यू लौटाएँ। दूसरे सेल नहीं बदल सकते, सेल फ़ॉर्मेट नहीं कर सकते, ईमेल नहीं भेज सकते।
- अनुमति माँगने वाली सेवाएँ नहीं — MailApp, GmailApp, DriveApp नहीं। (पब्लिक URL पर UrlFetchApp की अनुमति है।)
- हर कॉल की 30 सेकंड सीमा।
- Deterministic: सिर्फ़ आर्ग्युमेंट बदलने पर दोबारा गणना होती है। बिना आर्ग्युमेंट वाला
=MYFUNC()खुद रिफ़्रेश नहीं होगा। - सैकड़ों कॉल पर कुछ देर "Loading…" दिख सकता है — रेंज वाला रूप बेहतर है।
कामों (फ़ॉर्मेटिंग, ईमेल, कहीं और लिखना) के लिए मेन्यू या ट्रिगर वाला सामान्य फ़ंक्शन इस्तेमाल करें (अगला लेसन)।
6. एरर मैसेज
सेल में दिखाने के लिए एरर throw करें:
if (Number(rate) < 0) throw new Error('Rate cannot be negative');
सेल #ERROR! दिखाता है, माउस ले जाने पर आपका मैसेज।
आम गलतियाँ
@customfunction भूलना (चलता है, पर ऑटोकम्प्लीट मदद नहीं)। custom function के अंदर setValue की कोशिश ("You do not have permission")। कॉलम चाहिए था पर 1D array लौटाना — [[a],[b],[c]] लौटाएँ।