إدارة أكواد VBA لمصنف إكسل مشغل، مع ماكرو

إضافة وحدة VBA في Node.js

إن الكود النموذجي التالي ينشئ مصنفًا جديدًا ويضيف وحدة VBA جديدة وكود ماكرو ويحفظ الناتج بصيغة XLSM. بمجرد فتح ملف XLSM الناتج في Microsoft Excel والنقر على أوامر قائمة المطور > Visual Basic، سترى وحدة باسم “TestModule” وداخلها سترى كود الماكرو التالي.

Sub ShowMessage() {
    MsgBox "Welcome to Aspose!"
}

إليك الكود النموذجي لتوليد ملف XLSM الناتج مع وحدة VBA وكود الماكرو.

const path = require("path");
const AsposeCells = require("aspose.cells.node");

// The path to the documents directory.
const dataDir = path.join(__dirname, "data");

// Create new workbook
const workbook = new AsposeCells.Workbook();

// Access first worksheet
const worksheet = workbook.getWorksheets().get(0);

// Add VBA Module
const idx = workbook.getVbaProject().getModules().add(worksheet);

// Access the VBA Module, set its name and codes
const module = workbook.getVbaProject().getModules().get(idx);
module.setName("TestModule");

module.setCodes("Sub ShowMessage()" + "\r\n" +
"    MsgBox \"Welcome to Aspose!\"" + "\r\n" +
"End Sub");

// Save the workbook
workbook.save(path.join(dataDir, "output_out.xlsm"), AsposeCells.SaveFormat.Xlsm);

تعديل VBA أو ماكرو في Node.js

يحمّل الكود النموذجي التالي ملف Excel المصدر الذي يحتوي على كود VBA أو الماكرو التالي بداخله

Sub Button1_Click() {
    MsgBox "This is test message."
}

بعد تنفيذ رمز عينات Aspose.Cells، سيتم تعديل رمز VBA أو الماكرو مثل هذا

Sub Button1_Click() {
    MsgBox "This is Aspose.Cells message."
}

يمكنك تنزيل ملف Excel المصدر وملف Excel الناتج من الروابط المعطاة.

const path = require("path");
const AsposeCells = require("aspose.cells.node");

// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Create workbook object from source Excel file
const workbook = new AsposeCells.Workbook(path.join(dataDir, "sample.xlsm"));

// Change the VBA Module Code
const modules = workbook.getVbaProject().getModules();
const moduleCount = modules.getCount();
for (let i = 0; i < moduleCount; i++) {
const module = modules.get(i);
const code = module.getCodes();
if (code.includes("This is test message.")) 
{
code = code.replace("This is test message.", "This is Aspose.Cells message.");
module.setCodes(code);
}
}


// Save the output Excel file
workbook.save(path.join(dataDir, "output_out.xlsm"));

مواضيع متقدمة