Макросы для excel на javascript

For people using Excel 2016 or later version, there is an Excel add-in called Funfun in the add-in store that actually allows you to write and run JavaScript code directly in Excel. And of course, your JavaScript code also has access to the data stored in the spreadsheet. Here is a screenshot of how it looks like in Excel
2016.

enter image description here

Well in the middle of the interface you have a section in which you could write JavaScript, CSS and HTML code. It is pretty much like a playground built into the Excel. But the Funfun also has an online editor in which you could test with your code. You could see it in the pic below. I also posted the link of the example in the first picture so you could play with.

https://www.funfun.io/1/#/edit/5a4e0d461010eb73fe125c4e

enter image description here

What is special about the Funfun online editor is that it contains a ‘spreadsheet’ just like Excel. Though you can’t actually do any formatting in here, you could copy your data into the cells and test your code directly.

To use the data stored in the spreadsheet, all you need to do is to write some configuration in the short.io file of Funfun to tell JavaScript which area in the spreadsheet that contains your data. For example, in the example that I posted, all you need to write is

{
    "data": "=A2:B9"
}

And in the JavaScript code, an object called $internal is used to read the data. So in order to read the data that stored in A2:B9, you need to write

var data = $internal.data;

And its done. You could go to the documentation of Funfun if you want to know more.

If you are satisfied with the result you achieved in the online editor, you could easily load the result into you Excel using the URL above. Of couse first you need to insert the Funfun add-in from Insert — My add-ins. Here are some screenshots showing how you could do this.

enter image description here

enter image description here

Disclosure: I’m a developer of Funfun

Custom functions in Excel

Custom functions enable you to add new functions to Excel by defining those functions in JavaScript as part of an add-in. Users within Excel can access custom functions just as they would any native function in Excel, such as SUM().

This repository contains the source code used by the Yo Office generator when you create a new custom functions project. You can also use this repository as a sample to base your own custom functions project from if you choose not to use the generator. For more detailed information about custom functions in Excel, see the Custom functions overview article in the Office Add-ins documentation or see the additional resources section of this repository.

Debugging custom functions

This template supports debugging custom functions from Visual Studio Code. For more information see Custom functions debugging. For general information on debugging task panes and other Office Add-in parts, see Test and debug Office Add-ins.

Questions and comments

We’d love to get your feedback about this sample. You can send your feedback to us in the Issues section of this repository.

Questions about Office Add-ins development in general should be posted to Microsoft Q&A. If your question is about the Office JavaScript APIs, make sure it’s tagged with [office-js-dev].

Join the Microsoft 365 Developer Program

Get a free sandbox, tools, and other resources you need to build solutions for the Microsoft 365 platform.

  • Free developer sandbox Get a free, renewable 90-day Microsoft 365 E5 developer subscription.
  • Sample data packs Automatically configure your sandbox by installing user data and content to help you build your solutions.
  • Access to experts Access community events to learn from Microsoft 365 experts.
  • Personalized recommendations Find developer resources quickly from your personalized dashboard.

Additional resources

  • Custom functions overview
  • Custom functions best practices
  • Custom functions runtime
  • Office Add-ins documentation
  • More Office Add-ins samples at OfficeDev on Github

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Copyright

Copyright (c) 2019 Microsoft Corporation. All rights reserved.

I have been completely open and honest (as usual) about my contempt for the useless offerings that Microsoft has tried to pass for “Automation” in Excel using JavaScript.  Their concept of “Add-Ins” which do little more than allow you to add Web content inside your spreadsheet that interacts with the values in some cells in the file and exposes some inane answer in the Pane (pain?) on the right taking up even more of the screen already grabbed too much by the Effluent UI “Ribbon” at the top…

I have commented many times here, there and everywhere that what is REALLy needed is some kind of true Macro capability for the “Automation” of actual spreadsheets.  What a strange idea.  Well finally it appears as if someone at Microsoft has come to the same conclusion after years of apparently aimless brain-storming.  Excellent !!

Here is a link to my buddy Maarten Van Stam (a genuine Excel MVP btw) that details the recent “coming out” of this technology …

Office JS Public Preview is here!

and also here is more:

http://dev.office.com/blogs/Office-js-Public-Preview

and especially here:

(this last one you have to get into it until the interview with Rob Howard …)

Rob says some really interesting things … This MIGHT be a big thing but I am seen so many BIG THINGS over the years that have turned to nothing but smoke in the end.  But this is different I think … Is this a breakthrough in Microsoft’s approach to Excel?  ACTUALLY caring about people who ACTUALLY use the product ?

Hope so..

About Biggus Dickus

Dick is a consultant in London, ON Canada who specializes in Microsoft Excel and Microsoft Office Development.

This entry was posted in Analysis Services, Cloud, Excel, Office Automation, OLAP, PowerPivot, Process Automation, Spreadsheets, the Cloud, Uncategorized, VBA. Bookmark the permalink.

Вопрос:

Я хочу манипулировать Excel-таблицами с использованием макросов в Javascript, а не по умолчанию VBA. Я могу выполнить код javascript, используя следующий код VBA

'javascript to execute
Dim b As String
b = "function meaningOfLife(a,b) {return 42;}"

'VBA tool to run it
Dim o As New ScriptControl
o.Language = "JScript"
o.AddCode b
MsgBox o.Run("meaningOfLife", 0, 1)

это позволяет мне выполнить произвольный javascript, однако у меня нет доступа к электронной таблице excel из среды javascript. Есть ли способ, который я могу установить и получить значения листа в активном листе из javascript?

Лучший ответ:

Это зависит от того, что вы хотите делать “Программирование Excel”.

Если вы хотите управлять файлами Excel, вы можете сделать это через автоматизацию COM или даже ODBC в некоторой степени, используя JavaScript, запущенный в среде сценариев Windows.

Но если вы хотите, чтобы ваш код работал в активном сеансе Excel, что делает посетитель, у вас будет меньше вариантов.

См. этот вопрос. Я опубликовал несколько лет назад, когда у меня был JavaScript, который я хотел запустить в Excel, и у меня не было бюджета для преобразования в VBA:

Как использовать JavaScript в макросе Excel?

Ответ №1

Конечно, теперь в Excel 2013 вы имеете JavaScript API (http://zoom.it/UAzs#full) и можете взаимодействовать с электронной таблицей, используя панель задач и контент ПРОГРАММЫ.

Ответ №2

Для пользователей, использующих Excel 2016 или более позднюю версию, в надстройке есть надстройка Excel Funfun, которая фактически позволяет вам писать и запускать код JavaScript непосредственно в Excel. И, конечно, ваш код JavaScript также имеет доступ к данным, хранящимся в электронной таблице. Вот скриншот, как это выглядит в Excel
2016.

введите описание изображения здесь

В середине интерфейса у вас есть раздел, в котором вы можете писать JavaScript, CSS и HTML-код. Это похоже на детскую площадку, встроенную в Excel. Но у Funfun также есть онлайн-редактор, в котором вы можете протестировать свой код. Вы можете увидеть это на рис. Ниже. Я также разместил ссылку примера на первой картинке, чтобы вы могли играть.

https://www.funfun.io/1/#/edit/5a4e0d461010eb73fe125c4e

введите описание изображения здесь

Что особенно важно в онлайн-редакторе Funfun, так это то, что он содержит “таблицу”, как и Excel. Хотя вы вообще не можете форматировать, вы можете скопировать свои данные в ячейки и проверить свой код напрямую.

Чтобы использовать данные, хранящиеся в электронной таблице, все, что вам нужно сделать, это написать некоторую конфигурацию в файле short.io Funfun, чтобы рассказать JavaScript о том, какая область в электронной таблице содержит ваши данные. Например, в приведенном выше примере все, что вам нужно написать, это

{
"data": "=A2:B9"
}

И в коде JavaScript для чтения данных используется объект с именем $internal. Поэтому, чтобы прочитать данные, хранящиеся в A2: B9, вам нужно написать

var data = $internal.data;

И все сделано. Вы можете перейти к документации Funfu, если вы хотите узнать больше.

Если вы удовлетворены результатом, достигнутым в онлайн-редакторе, вы можете легко загрузить результат в Excel, используя указанный выше URL. Сначала вам нужно вставить надстройку Funfun из Вставить – Мои надстройки. Вот несколько скриншотов, показывающих, как вы могли это сделать.

введите описание изображения здесь

введите описание изображения здесь

Раскрытие информации: Я разработчик Funfun

Ответ №3

Попробуйте Excel-DNA для программного интерфейса для Excel. Еще два хороших инструментария – xlwings и Excel-REPL, которые поддерживают интерфейс Python и Clojure соответственно.

Старый

06.07.2012, 10:58

Интересующийся

Отправить личное сообщение для klicken

Посмотреть профиль

Найти все сообщения от klicken

 

Регистрация: 06.07.2012

Сообщений: 12

макрос для Excel в javascript

Подскажите пожалуйста как лучше переделать этот макрос на javascript

Sub test()
With Application
.UseSystemSeparators = True
End With
Dim LastCell As Range: Set LastCell = Range(«B65536»).End(xlUp).Offset(1)
LastCell.FormulaR1C1 = «=SUM(R1C:R[-1]C)»
LastCell.AutoFill LastCell.Resize(, 2)
LastCell.EntireRow.Cells(1) = «Итог:»

End Sub

Ответить с цитированием

Старый

06.07.2012, 11:07

Интересующийся

Отправить личное сообщение для klicken

Посмотреть профиль

Найти все сообщения от klicken

 

Регистрация: 06.07.2012

Сообщений: 12

Может это глупый вопрос)
Подскажите тогда где почитать про это

Ответить с цитированием

Старый

06.07.2012, 11:26

Аватар для lord2kim

Профессор

Отправить личное сообщение для lord2kim

Посмотреть профиль

Найти все сообщения от lord2kim

 

Регистрация: 03.05.2011

Сообщений: 848

Подскажите пожалуйста как лучше переделать этот макрос на javascript

Sub test()
With Application
.UseSystemSeparators = True
End With
Dim LastCell As Range: Set LastCell = Range(«B65536»).End(xlUp).Offset(1)
LastCell.FormulaR1C1 = «=SUM(R1C:R[-1]C)»
LastCell.AutoFill LastCell.Resize(, 2)
LastCell.EntireRow.Cells(1) = «Итог:»

End Sub

не на javascript, а на JScript)
а что он делает то?)
много чего есть в книге VBA и программирование в MS Office для пользователей

Ответить с цитированием

Старый

06.07.2012, 11:33

Интересующийся

Отправить личное сообщение для klicken

Посмотреть профиль

Найти все сообщения от klicken

 

Регистрация: 06.07.2012

Сообщений: 12

Sub test()
With Application
.UseSystemSeparators = True //устанавливает системный разделитель, чтобы у всех пользователей была «.» между целой и дробной части в числах
End With
Dim LastCell As Range: Set LastCell = Range(«B65536»).End(xlUp).Offset(1)
LastCell.FormulaR1C1 = «=SUM(R1C:R[-1]C)»
LastCell.AutoFill LastCell.Resize(, 2)
LastCell.EntireRow.Cells(1) = «Итог:»
// находит последнее число в столбце, и в пустую ячейку записывает сумму столбца
End Sub

Ответить с цитированием

Старый

06.07.2012, 11:34

Аватар для lord2kim

Профессор

Отправить личное сообщение для lord2kim

Посмотреть профиль

Найти все сообщения от lord2kim

 

Регистрация: 03.05.2011

Сообщений: 848

Сообщение от klicken
Посмотреть сообщение

Подскажите пожалуйста как лучше переделать этот макрос на javascript

Sub test()
With Application
.UseSystemSeparators = True
End With
Dim LastCell As Range: Set LastCell = Range(«B65536»).End(xlUp).Offset(1)
LastCell.FormulaR1C1 = «=SUM(R1C:R[-1]C)»
LastCell.AutoFill LastCell.Resize(, 2)
LastCell.EntireRow.Cells(1) = «Итог:»

End Sub

function test() {
	with (Application) {
		.UseSystemSeparators = true;
	}
	var LastCell = Range("B65536").End(xlUp).Offset(1);
	LastCell.FormulaR1C1 = "=SUM(R1C:R[-1]C)";
	LastCell.AutoFill LastCell.Resize(, 2);
	LastCell.EntireRow.Cells(1) = "Итог:";
}

Ответить с цитированием

Старый

06.07.2012, 11:38

Интересующийся

Отправить личное сообщение для klicken

Посмотреть профиль

Найти все сообщения от klicken

 

Регистрация: 06.07.2012

Сообщений: 12

Спасибо большое!

Ответить с цитированием

Старый

06.07.2012, 11:41

Интересующийся

Отправить личное сообщение для klicken

Посмотреть профиль

Найти все сообщения от klicken

 

Регистрация: 06.07.2012

Сообщений: 12

<html>
<head>
<input type=’button’ value=’Excel’;
onClick=»javascript:
var xls = new ActiveXObject ( ‘Excel.Application’ );
xls.visible = true;
var newBook = xls.Workbooks.Add;
newBook.Worksheets.Add;
newBook.Worksheets(1).Activate;
newBook.Worksheets(1).Cells(1,1).value=’1.25, 3.82′;
newBook.Worksheets(1).Cells(2,1).value=’2.1, 1′;
newBook.Worksheets(1).Cells(1,2).value=’1, 4′;
newBook.Worksheets(1).Cells(2,2).value=’10 , 12′;
newBook.Worksheets(1).Name=’WorkSheet from Javascript’;

function test() {
with (Application) {
.UseSustemSeparators = true;
}
var LastCell = Range(‘B65536’).End(xlUp).Offset(1);
LastCell.FormulaR1C1 = ‘=SUM(R1C:R[-1]C)’;
LastCell.AutoFill LastCell.Resize(, 2);
LastCell.EntireRow.Cells(1) = ‘Итог:’;
}
«

// newBook.Worksheets(1).SaveAs(‘C:\temp\TEST2.XLS’ );

</head>
</html>

как его модернизировать?)

Ответить с цитированием

Старый

06.07.2012, 11:50

Аватар для lord2kim

Профессор

Отправить личное сообщение для lord2kim

Посмотреть профиль

Найти все сообщения от lord2kim

 

Регистрация: 03.05.2011

Сообщений: 848

Сообщение от klicken
Посмотреть сообщение

<html>
<head>
<input type=’button’ value=’Excel’;
onClick=»javascript:
var xls = new ActiveXObject ( ‘Excel.Application’ );
xls.visible = true;
var newBook = xls.Workbooks.Add;
newBook.Worksheets.Add;
newBook.Worksheets(1).Activate;
newBook.Worksheets(1).Cells(1,1).value=’1.25, 3.82′;
newBook.Worksheets(1).Cells(2,1).value=’2.1, 1′;
newBook.Worksheets(1).Cells(1,2).value=’1, 4′;
newBook.Worksheets(1).Cells(2,2).value=’10 , 12′;
newBook.Worksheets(1).Name=’WorkSheet from Javascript’;

function test() {
with (Application) {
.UseSustemSeparators = true;
}
var LastCell = Range(‘B65536’).End(xlUp).Offset(1);
LastCell.FormulaR1C1 = ‘=SUM(R1C:R[-1]C)’;
LastCell.AutoFill LastCell.Resize(, 2);
LastCell.EntireRow.Cells(1) = ‘Итог:’;
}
«

// newBook.Worksheets(1).SaveAs(‘C:\temp\TEST2.XLS’ );

</head>
</html>

как его модернизировать?)

<html>
<head>
<title>Excel</title>
<script>
function test() {
	var xls = new ActiveXObject ( 'Excel.Application' );
	xls.visible = true;
	var newBook = xls.Workbooks.Add;
	newBook.Worksheets.Add;
	newBook.Worksheets(1).Activate;
	newBook.Worksheets(1).Cells(1,1).value='1.25, 3.82';
	newBook.Worksheets(1).Cells(2,1).value='2.1, 1';
	newBook.Worksheets(1).Cells(1,2).value='1, 4';
	newBook.Worksheets(1).Cells(2,2).value='10 , 12';
	newBook.Worksheets(1).Name='WorkSheet from Javascript';
	
	with (Application) {  
		.UseSustemSeparators = true;  
	}  
	var LastCell = Range('B65536').End(xlUp).Offset(1);  
	LastCell.FormulaR1C1 = '=SUM(R1C:R[-1]C)';  
	LastCell.AutoFill LastCell.Resize(, 2);  
	LastCell.EntireRow.Cells(1) = 'Итог:';  
}
</script>
</head>
<body>
<input type='button' value='Excel' onClick="test()">
</body>
</html>

и лучше все это запихнуть в HTML Application (.hta), чтобы никаких запросов на разрешение выполнения ActiveX-объектов не появлялось…

Ответить с цитированием

Старый

06.07.2012, 12:07

Интересующийся

Отправить личное сообщение для klicken

Посмотреть профиль

Найти все сообщения от klicken

 

Регистрация: 06.07.2012

Сообщений: 12

Сообщение от lord2kim
Посмотреть сообщение

<html>
<head>
<title>Excel</title>
<script>
function test() {
	var xls = new ActiveXObject ( 'Excel.Application' );
	xls.visible = true;
	var newBook = xls.Workbooks.Add;
	newBook.Worksheets.Add;
	newBook.Worksheets(1).Activate;
	newBook.Worksheets(1).Cells(1,1).value='1.25, 3.82';
	newBook.Worksheets(1).Cells(2,1).value='2.1, 1';
	newBook.Worksheets(1).Cells(1,2).value='1, 4';
	newBook.Worksheets(1).Cells(2,2).value='10 , 12';
	newBook.Worksheets(1).Name='WorkSheet from Javascript';
	
	with (Application) {  
		.UseSustemSeparators = true;  
	}  
	var LastCell = Range('B65536').End(xlUp).Offset(1);  
	LastCell.FormulaR1C1 = '=SUM(R1C:R[-1]C)';  
	LastCell.AutoFill LastCell.Resize(, 2);  
	LastCell.EntireRow.Cells(1) = 'Итог:';  
}
</script>
</head>
<body>
<input type='button' value='Excel' onClick="test()">
</body>
</html>

и лучше все это запихнуть в HTML Application (.hta), чтобы никаких запросов на разрешение выполнения ActiveX-объектов не появлялось…

Спасибо, сохранил как Вы и сказали, debugger выдает ошибку после нажатия на кнопку Excel …

Ответить с цитированием

Старый

06.07.2012, 12:26

Аватар для lord2kim

Профессор

Отправить личное сообщение для lord2kim

Посмотреть профиль

Найти все сообщения от lord2kim

 

Регистрация: 03.05.2011

Сообщений: 848

Сообщение от klicken
Посмотреть сообщение

Спасибо, сохранил как Вы и сказали, debugger выдает ошибку после нажатия на кнопку Excel …

уберите первую точку в 18строке
в 22 строке все так и должно быть даже на VBA?

LastCell.AutoFill LastCell.Resize(, 2);

AutoFill() это метод для автоматического заполнения диапазона [читать здесь], и в скобках перед запятой наверно тоже цифорки не хватает [читать здесь]

LastCell.AutoFill(); LastCell.Resize(3, 2);

Ответить с цитированием

Понравилась статья? Поделить с друзьями:
  • Макросы для excel для поиска совпадений
  • Макросы для excel выделение строки
  • Макросы в excel примеры обучение
  • Макросы в excel примеры использования
  • Макросы в excel примеры готовые скачать