简体   繁体   English

VBA 对于每个循环到 Excel JavaScript ZDB974238714CA8DE634A7CE1D083A14 代码

[英]VBA For Each Loop to Excel JavaScript API Code

在此处输入图像描述

In the following VBA code, I debug.print each cell value.在下面的 VBA 代码中,我 debug.print 每个单元格值。 Using the data in the picture, my answer appears like this.使用图片中的数据,我的答案是这样的。

Sub loopAndDebugPrintEachCell()
Dim cl As Object
With Sheets("Sheet1")
    For Each cl In .Range("A1:D2")
        Debug.Print cl.Value
    Next cl
End With
End Sub

在此处输入图像描述

I am trying to reiterate this code in JavaScript and I figured out a solution, but I am not sure that this is the most efficient way.我试图在 JavaScript 中重申此代码,并且我想出了一个解决方案,但我不确定这是最有效的方法。 I am getting the exact same answer, but is there a more advantageous way to loop through a range?我得到了完全相同的答案,但是有没有更有利的方式来循环遍历一个范围?

  loopAndConsoleLogEachCell = async () => {
    try {
      await Excel.run(async context => {
        const range = context.workbook.worksheets.getItem("Sheet1").getRange("A1:D2");
        range.load(["columnCount", "rowCount"]);
        await context.sync();
        let i = 0;
        let rowC = 0;
        do {
          let loopRng = range.getAbsoluteResizedRange(1, 1).getOffsetRange(rowC, i).load(["values"]);
          await context.sync();
          console.log(`${loopRng.values} `);
          let rangeColCount = Math.floor(((range.columnCount) / 2) + 1);
          if (rowC < (range.rowCount) && i == (rangeColCount)) {
            rowC++;
            i = 0;
          } else {
            i++;
          }
        }
        while (rowC < range.rowCount && i < range.columnCount);
      });
    } catch (error) {
      console.error(error);
    }
  };

If you want to print the value of each cell in the range, you could use range.values API如果要打印范围内每个单元格的值,可以使用range.values API

Here is the sample code for getting the values for the range这是获取范围值的示例代码

  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getItem("Sample");
    const range = sheet.getRange("B2:E6");
    range.load("text");
    range.load("values");

    await context.sync();
    console.log(range.values);
    //console.log(JSON.stringify(range.text, null, 4));
  });

The document can be found https://docs.microsoft.com/en-us/javascript/api/excel/excel.range?view=excel-js-preview#values该文档可以找到https://docs.microsoft.com/en-us/javascript/api/excel/excel.range?view=excel-js-preview#values

VBA allows you to access every cell on the iteration using the for loop. VBA 允许您使用 for 循环访问迭代中的每个单元格。 What I did in TypeScript to replicate this for a range was loading the properties of columns and rows and storing the values in variables:我在 TypeScript 中为某个范围复制此内容所做的是加载列和行的属性并将值存储在变量中:

await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
const range = context.workbook.getSelectedRange();
range.load(["columnIndex", "columnCount", "rowCount", "rowIndex"]);
let col_1 = range.columnIndex; //first column index
let nc = range.columnCount; //number of columns
let row_1 = range.rowIndex; //first row
let nr = range.rowCount; //number of rows

Then you can access each cell with two for loops:然后您可以使用两个 for 循环访问每个单元格:

for (let r = 0; r < nr; r++) {
      for (let c = 0; c < nc; c++) {
         cell = sheet.getCell(r + row_1, c + col_1);
         cell.load(["address", "values", "formulasR1C1", "format"]);
         await context.sync();
         let cell_add = cell.address;
         let cell_val = cell.values[0][0]; //values of a cell/range is always a matrix
         if (cell_val <= 5) {
         //do something
         }
      }
  };

The code might not be the best, but it worked for me.该代码可能不是最好的,但它对我有用。

Hope this helps.希望这可以帮助。

Here is an example I used to iterate over a range, only using one context.sync() to find a cell match via RegEx which should illustrate how to use a For Each Cell loop.这是我用来迭代一个范围的示例,仅使用一个context.sync()通过RegEx查找单元格匹配,这应该说明如何使用For Each Cell循环。 Keep in mind I am new to JS as well, but I believe this is proper method.请记住,我也是 JS 的新手,但我相信这是正确的方法。

function Bool_RegEx(rexp, findstr) {
    return rexp.test(findstr)
}

function Make_FakeData(context) {
    var ws = context.workbook.worksheets.getActiveWorksheet();
    var rng = ws.getRange("A1:D5");
    rng.values = "TESTDATA";

    var rng = ws.getRange("A5");
    rng.values = "AB12345678"
    return context;
}

export async function helloworld(event) {
    try {
        await Excel.run(async (context) => {
            //Start Func
            Make_FakeData(context);

            var ws = context.workbook.worksheets.getActiveWorksheet();
            var rng = ws.getRange("A1:D5");
            rng.load(["columnCount", "rowCount", "values"]);

            let rexp = new RegExp('[a-z]{2}[0-9]{8}', 'i');
            return context.sync()
                .then(function () {
                    for (var r = 0; r < rng.rowCount; ++r) {
                        for (var c = 0; c < rng.columnCount; ++c) { 
                        var rcellval = rng.values[r][c];
                        console.log("r = " + r);
                        console.log("c = " + c);
                        console.log("rcellval = " + rcellval);
                        if (Bool_RegEx(rexp, rcellval) === true) {
                            console.log("RegEx Match in Row r" + r + ", Col " + c);
                            console.log("RegEx Match rcellval = " + rcellval);
                        }
                    }
                }

                })

            //End Func
            await context.sync();
        });
    } catch (error) {
        console.error(error);
    }
    event.completed();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM