Hướng dẫn Scripts Điền Hàng Loạt Google Sheets

Hướng dẫn tạo Scripts "Điền Hàng Loạt" trong Google Sheets

Hướng dẫn này giúp bạn tạo nhanh công cụ "Điền hàng loạt" vào Google Sheets để cập nhật số tiền chi tiêu quảng cáo cho các tài khoản dựa trên ID.

Hướng dẫn truy cập và tạo file Scripts

  1. Mở file Google Sheets của bạn.
  2. Vào menu Tiện ích mở rộng → chọn Apps Script.
  3. Google sẽ mở một tab mới chứa trình soạn thảo mã code.
  4. Ở góc trái trên cùng, click chuột phải vào file mặc định Code.gs → chọn Đổi tên → nhập tên file là menu.gs để dễ quản lý.
  5. Sau đó bấm dấu + để tạo thêm file mới tương ứng như hướng dẫn bên dưới.

Bước 1: Tạo file menu.gs

File này tạo Menu trên thanh công cụ Google Sheets để gọi các scripts.

Hiển thị / Ẩn code

Bước 2: Tạo file BulkFill.gs

File này xử lý logic chính: Mở Sidebar và xử lý cập nhật dữ liệu.

Hiển thị / Ẩn code
function bulkFillSidebar() {
  const html = HtmlService.createHtmlOutputFromFile('BulkFillSidebar')
    .setTitle('Điền hàng loạt')
    .setWidth(350);
  SpreadsheetApp.getUi().showSidebar(html);
}

function bulkFillData(searchCol, fillCol, dataText) {
  const sheet = SpreadsheetApp.getActiveSheet();
  const lastRow = sheet.getLastRow();
  const searchColIndex = columnToIndex(searchCol);
  const fillColIndex = columnToIndex(fillCol);

  if (searchColIndex < 1 || fillColIndex < 1) {
    return { success: false, message: '❌ Sai định dạng cột. Vui lòng nhập ký tự A-Z.' };
  }

  const rows = dataText.trim().split('\n');
  const mapData = {};
  const results = [];

  for (let row of rows) {
    const parts = row.trim().split(/\s+/);
    if (parts.length !== 2) {
      results.push({ id: row, status: '❌ lỗi định dạng' });
      continue;
    }
    mapData[parts[0].toLowerCase()] = parts[1];
  }

  const values = sheet.getRange(1, searchColIndex, lastRow).getValues();
  let count = 0;

  for (let key in mapData) {
    let matched = false;
    for (let i = 0; i < values.length; i++) {
      const cellValue = (values[i][0] || '').toString().toLowerCase().trim();
      if (cellValue === key) {
        const newValue = mapData[key];
        const currentValue = sheet.getRange(i + 1, fillColIndex).getValue();
        if (currentValue !== newValue) {
          sheet.getRange(i + 1, fillColIndex).setValue(newValue);
        }
        results.push({ id: key, status: '✅ đã điền' });
        matched = true;
        count++;
        break;
      }
    }
    if (!matched) {
      results.push({ id: key, status: '❌ lỗi - không tìm thấy ID' });
    }
  }

  return {
    success: true,
    message: `✅ Đã cập nhật ${count} dòng.`,
    results: results
  };
}

function columnToIndex(letter) {
  letter = letter.toUpperCase().trim();
  if (!letter.match(/^[A-Z]+$/)) return -1;
  let index = 0;
  for (let i = 0; i < letter.length; i++) {
    index = index * 26 + (letter.charCodeAt(i) - 64);
  }
  return index;
}

Bước 3: Tạo file BulkFillSidebar.html

File này thiết kế giao diện Sidebar nhập ID và Số tiền muốn điền.

Hiển thị / Ẩn code
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
      body { font-family: Arial, sans-serif; padding: 10px; }
      input, textarea { width: 100%; margin: 5px 0; }
      button { margin-top: 10px; }
      #status { margin-top: 10px; font-weight: bold; }
      ul#log { margin-top: 10px; padding-left: 20px; }
      ul#log li { font-size: 14px; }
    </style>
  </head>
  <body>
    <h3>Điền hàng loạt</h3>
    <label>Cột chứa ID (Ví dụ: A)</label>
    <input type="text" id="searchCol">

    <label>Cột cần điền Số tiền (Ví dụ: B)</label>
    <input type="text" id="fillCol">

    <label>Danh sách ID và Số tiền (Mỗi dòng: ID SốTiền)</label>
    <textarea id="dataText" rows="10" placeholder="vd:\nID1 400\nID2 222"></textarea>

    <button onclick="bulkFill()">Thực hiện Điền</button>

    <div id="status"></div>
    <ul id="log"></ul>

    <script>
      function bulkFill() {
        const searchCol = document.getElementById('searchCol').value;
        const fillCol = document.getElementById('fillCol').value;
        const dataText = document.getElementById('dataText').value;

        document.getElementById('status').innerHTML = '⏳ Đang xử lý...';
        document.getElementById('log').innerHTML = '';

        google.script.run.withSuccessHandler(function(result) {
          document.getElementById('status').innerHTML = result.message;

          if (result.results && result.results.length > 0) {
            const log = document.getElementById('log');
            result.results.forEach(item => {
              const li = document.createElement('li');
              li.textContent = `${item.id}: ${item.status}`;
              li.style.color = item.status.includes('✅') ? 'green' : 'red';
              log.appendChild(li);
            });
          }
        }).bulkFillData(searchCol, fillCol, dataText);
      }
    </script>
  </body>
</html>

Bước 4: Triển khai và sử dụng

Sau khi hoàn tất các file:

  1. Lưu lại toàn bộ file trên Google Apps Script.
  2. Reload lại Google Sheets.
  3. Vào menu 🔧 Chạy Scripts → chọn 📝 Điền hàng loạt.
  4. Nhập dữ liệu vào Sidebar theo định dạng:
ID1 400
ID2 300
ID3 500

Nhấn nút "Thực hiện Điền" để scripts tự động xử lý.

Kết quả sẽ hiển thị trong Sidebar:

  • ✅ ID1: đã điền
  • ❌ ID2: lỗi - không tìm thấy ID

Chúc bạn thực hiện thành công!

You cannot copy content of this page