Hi...I have finally got the following Apps Script code to work. However, I also want it to automatically transfer the active spreadsheet name to the new Google Form file name and Form title in order to avoid manually replacing 'Quiz Form' in Line 10 every time I run the code:
function createQuizFromSheet() {
// Get the active spreadsheet and sheet
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
// Get all the data from the sheet, skipping the header row
const data = sheet.getDataRange().getValues().slice(1);
// Create a new Google Form
const form = FormApp.create('Quiz Form');
form.setIsQuiz(true); // Turn the form into a quiz
// Loop through each row of data (each question)
data.forEach(row => {
// Extract question details from the row
const questionTitle = row[0];
const choices = row.slice(1, 5); // Choices A-D
const correctAnswerLetter = row[5];
const points = row[6];
// Convert the letter to index for correct choice
let correctAnswerIndex = 0;
if (correctAnswerLetter === "B") correctAnswerIndex = 1;
if (correctAnswerLetter === "C") correctAnswerIndex = 2;
if (correctAnswerLetter === "D") correctAnswerIndex = 3;
// Add multiple choice question to the form
const item = form.addMultipleChoiceItem()
.setTitle(questionTitle);
// Create choices, mark the correct one and set points
const choiceItems = [];
for(let i = 0; i< choices.length; i++){
if (choices[i]){ //only create if the choice is not blank
choiceItems.push(item.createChoice(choices[i], i === correctAnswerIndex));
}
}
item.setChoices(choiceItems);
item.setPoints(points);
});
// Get and log the form's published URL
const formUrl = form.getPublishedUrl();
Logger.log('Form URL: ' + formUrl);
// Optional: Display form URL in the spreadsheet
// sheet.getRange(1, 8).setValue('Form URL'); // Set header
// sheet.getRange(2, 8).setValue(formUrl); // Output URL