Search code examples
exceloffice-jsexcel-addins

How to check if cell if empty in Office.js


I have just started with Office Addins and I'm experimenting with the functionalities. I have several VBA Userforms that I would want to replace with popups from the Office add-in.

I am using the following code to enter a string into a cell(nothing fancy, I know) but I would want to check if the cell if empty before passing the value. If it is, enter (arg.message).

the problem I have encountered: with if (range.value == "") the value is being set in "A4" even if "A3" if empty; with if (range.value == " ") the value is not being entered in any cells.

Can anyone give me an example of how to check if a cell is empty? I know it seems trivial but I have only found examples of how to check with col and row numbers for conditional formatting. I am trying to test all these functionalities to be able to start moving stuff from VBA to OfficeJS.

Thanks, Mike

function processMessage(arg) {      
    console.log(arg.message);
    $('#user-name').text(arg.message);
    dialog.close();
    Excel.run(function (context) {
        var sheet = context.workbook.worksheets.getItem("Sheet1");
        var range = sheet.getRange("A3");
        if (range.value == "") {
            range.values = (arg.message);
            range.format.autofitColumns(); 
            return context.sync();
        } else {
            range.getOffsetRange(1, 0).values = (arg.message)
            return context.sync();
        }

    }).catch(errorHandler);
}

PS: the whole code in case there is something wrong somewhere else

   (function () {
            "use strict";
            // The initialize function must be run each time a new page is loaded.
            Office.initialize = function (reason) {
                $(document).ready(function () {

                    // Add a click event handler for the button.
                    $('#popup-button').click(opensesame);
                    $('#simple-button').click(function () {
                        Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
                        function (result) {
                            if (result.status === Office.AsyncResultStatus.Succeeded) {
                                $("#banner-text").text('The selected text is: "' + result.value + '"');
                                $("#banner").show(result.value);
                                console.log()
                            } else {
                                $("#banner-text").text('Error: ' + result.error.message);
                                $("#banner").show();
                            }
                        });
                    });

                    $("#banner-close").click(function () { $("#banner").hide(); });
                    $("#banner").hide();
                });
            }

            let dialog = null;

    function opensesame() {
        Office.context.ui.displayDialogAsync(
            'https://localhost:3000/popup.html',
            { height: 35, width: 25 },

            function (result) {
                dialog = result.value;
                dialog.addEventHandler(Microsoft.Office.WebExtension.EventType.DialogMessageReceived, processMessage);
            }
        );
    }

    function processMessage(arg) {


        console.log(arg.message);
        $('#user-name').text(arg.message);
        dialog.close();
        Excel.run(function (context) {
            var sheet = context.workbook.worksheets.getItem("Sheet1");
            var range = sheet.getRange("A3");
            if (range.value == "") {
                range.values = (arg.message);
                range.format.autofitColumns(); 
                return context.sync();
            } else {
                range.getOffsetRange(1, 0).values = (arg.message)
                return context.sync();
            }

        }).catch(errorHandler);
    }

        })();

Solution

  • The Range object has a values property, but not a value property. So range.value in your condition test is undefined which does not match an empty string; hence the else clause runs.

    A couple of other things:

    1. Your condition tries to read a property of the range object. You have to load the property and call context.sync before you can read the property.
    2. The value of the range.values property is a two-dimensional array (although it may have a single value in it if the range is a single cell). It is not a string, so comparing it with an empty string will always be false.

    If I understand your goal, I think you should be testing with whether range.values (after you load it and sync) has an empty string in it's only cell. For example, if (range.values[0][0] === ""). Even better from a performance standpoint is to load the range.valueTypes property (and sync) and then compare like this: if (range.valueTypes[0][0] === Excel.RangeValueType.empty).