23
1 DataNitro Contents: Cell 1. Instantiation 2. Properties 3. Font Formatting 4. Methods 5. Ordering 6. Range Syntax 7. Active Cell 8. Unicode CellRange 1. Instantiation 2. Properties 3. Methods Worksheets 1. Active Sheet 2. Display Sheet 3. Clear/Delete row/column 4. Insert row/column 5. Sheet functions 6. Merging Cells 7. Pivot Tables 8. Saving User Defined Functions 1. Overview 2. Input and Output 3. Notes VBA 1. Calling VBA from DataNitro 2. Calling DataNitro from VBA 3. Sheets: name and codenameCell

excel addon

Embed Size (px)

Citation preview

Page 1: excel addon

1

DataNitro Contents:

Cell

1. Instantiation

2. Properties

3. Font Formatting

4. Methods

5. Ordering

6. Range Syntax

7. Active Cell

8. Unicode

CellRange

1. Instantiation

2. Properties

3. Methods

Worksheets

1. Active Sheet

2. Display Sheet

3. Clear/Delete row/column

4. Insert row/column

5. Sheet functions

6. Merging Cells

7. Pivot Tables

8. Saving

User Defined Functions

1. Overview

2. Input and Output

3. Notes

VBA

1. Calling VBA from DataNitro

2. Calling DataNitro from VBA

3. Sheets: name and codenameCell

Page 2: excel addon

2

CellCellCellCell The "Cell" class represents a single cell of an Excel spreadsheet.

1. Instantiation1. Instantiation1. Instantiation1. Instantiation

There are several ways to instantiate a cell:

1. With a (row, column) pair or tuple.

e.g: Cell(2,1) and Cell((2,1)) return the cell "A2".

2. By name.

e.g: Cell("A2") returns the cell "A2".

3. By entering a range. This will return the first cell in the range.

e.g: Cell("A2:A10^A3:B5,A4,C3") returns the cell "A3".

4. By entering a named range. This will return the first cell in the range. Named

ranges must be on the sheet passed to Cell (or the active sheet).

e.g: Cell("Use_VBA") will return the cell "NOT1993" if "Use_VBA" is the range

"NOT1993:NOT1995".

By default, cells are on the active worksheet. To use a different worksheet, pass its name as the first argument when calling Cell, or change the active sheet. e.g: Cell("Sheet2",2,1) or Cell("Sheet2","A2") will return the cell "A2" on sheet 2.

2. Properties2. Properties2. Properties2. Properties

Cells have a number of associated properties. row, col, position, sheet and name are set when the cell is created, and should not be changed. row returns the Cell's row, col and column return its column, and position returns (row, column) as a tuple. Cell("A2").row = 2 Cell("A2").col = 1 Cell("A2").column = 1 Cell("A2").position = (2, 1)

Page 3: excel addon

3

sheet returns a cell's sheet. e.g: If Sheet1 is active, Cell("A2").sheet will return "Sheet1". name returns a cell's name. e.g: Cell("A2").name and Cell(2,1).name both return "A2". ValueValueValueValue value returns and sets the value of a cell. If you want to set a cell to evaluate an Excel formula, you should use formula. A blank cell will return None. e.g: Cell("A3").value will return 42 if the cell A3 is set to 42, or contains a formula which evaluates to 42. Cell("A3").value will return None if A3 is empty. (This won't print anything if run in the shell.) Cell("A3").value = "cake" will set the value of A3 to "cake".

Horizontal & VerticalHorizontal & VerticalHorizontal & VerticalHorizontal & Vertical

Getting Cell("A1").horizontal returns the list of values starting in A1 and ending immediately before the first cell to the right of A1 that's empty. Setting Cell("A1").horizontal to an iterable will set A1 to the first value of the iterable, B1 to the second value, etc. Getting and setting vertical does the same for columns. e.g: Cell("A1").vertical = [3, 1, 4, 1, 5] will set A1 to 3, A2 to 1, A3 to 4, A4 to 1, and A5 to 5. If A6 is empty, calling Cell("A1").vertical afterwards will return [3, 1, 4, 1, 5]. FormulaFormulaFormulaFormula formula returns and sets the formula of a cell. You can set a cell's formula by passing the formula as a string; you should use value to pass non-formula values. If you query a cell with no formula, it will return its value instead. e.g: If A3 contains the formula '=A1*(A2-2)', Cell("A3").formula will return '=A1*(A2-2)'. In contrast Cell("A3").value will return 42 if A1 = 6 and A2 = 9.

Page 4: excel addon

4

Cell("B5").formula = "=SUM(B1:B4)" will set the value of B5 to the sum of the values of B1 through B4.

DateDateDateDate

If a cell has a date in it, date will return a Python datetime.date object. Otherwise, it will return the value in the cell. Setting date is identical to setting a Cell's value. e.g: If A1 contains the string '2/29/2012', Cell("A1").date will return datetime.date(2012, 2, 29). If it contains the string '2/29/2013', Cell("A1").date will return '2/29/2013'. CommentsCommentsCommentsComments comment will get and set the comment in a cell. Setting a comment to an empty string removes it. e.g: Cell("A1").comment = 'this is a \n comment.' will set the comment in A1 to: this is a comment. Cell("A1").comment will then return 'this is a \n comment.' To see the comment formatted properly, you should print it.

AlignmentAlignmentAlignmentAlignment

A cell can have one of five alignments: left, right, center, justify, and general. Alignment is 'general' by default, and you can set it to any of the other four values. >>> Cell("A1").alignment 'general' >>> Cell("A1").alignment = 'center' >>> Cell("A1").alignment 'center'

Page 5: excel addon

5

ColorColorColorColor color returns and sets the color of a cell. Excel stores colors as 24 bit numbers, with the first two hexadecimal digits describing the amount of red, the next two the amount of green, and the last two the amount of blue, like html. You can pass 24 bit numbers to color as hexadecimal numbers, strings, or regular numbers. e.g: Cell("A1").color = 0xFF0000 will set the color of A1 to red. Cell("B2").color = "0xEF00FF" and Cell("B2").color = 15663359 will set B2 to pink. DataNitro also recognizes 16 predefined colors: black, white, red, blue, green, yellow, purple, gray, silver, maroon, olive, lime, teal, aqua, navy, and fuchsia. You can see these color names by printing Cell.COLORS(), which prints ['BLACK', 'GRAY', 'SILVER', 'WHITE', 'MAROON', 'RED', 'OLIVE', 'YELLOW', 'GREEN', 'LIME', 'TEAL', 'AQUA', 'NAVY', 'BLUE', 'PURPLE', 'FUCHSIA'] e.g. Cell("C3").color = 'olive' will set C3 to olive. Cell("C3").color = 'teal' will set C3 to teal.

3. Font Formatting3. Font Formatting3. Font Formatting3. Font Formatting

The font property of a cell is a class that controls a cell's font. font has the following properties: color, size, bold, italic, underline, strikethrough, subscript, and superscript. Printing font will print a cell's font color, size, and any active font styles. e.g: print Cell("A1").font will print font color: black, font size: 11 if A1 has not had any changes to its font. If A2 has a red, size 8 font with bold, italic, and superscript turned on, print Cell("A2").font will print font color:red, font size: 8, bold, italic, superscript. Font SizeFont SizeFont SizeFont Size: size gets and sets font sizes. If a cell has text of more than one size, this will return 0. e.g: Cell("A1").font.size = 409 will make the text in cell A1 very large. Font ColorFont ColorFont ColorFont Color: color gets and sets font colors. This accepts colors in the same format as Cell.color. If a cell has mixed colors, font.color will return 'black'. e.g: Cell("A1").font.color = 'red' will make the text in A1 red.

Page 6: excel addon

6

Font StylesFont StylesFont StylesFont Styles: Calling any of bold, italic, underline, strikethrough, subscript, and superscript will return True if the property is on for the cell, and False if it's off. A value passed to the Cell will be interpreted as a boolean (i.e. 0, '', [ ], and () evaluate to False, nonempty containers and non-zero numbers evaluate to True). If a cell has mixed formatting (e.g. part bold and part not bold), the associated style will return True. If a cell has mixed superscript and/or subscripts, both superscript and subscript will return True. e.g: Cell("A1").font.bold will return True if the cell has bolded text, and False if it doesn't. Cell("A1").font.bold = True, Cell("A1").font.bold = 1, and Cell("A1").font.bold = (9,3) will set A1 to bold. Cell("B1").font.italic = False, Cell("B1").font.italic = 0, and Cell("B1").font.italic = () will turn off italics in B1. Notes:Notes:Notes:Notes: Excel supports a maximum of 512 different fonts. Setting more than this number of fonts will cause Excel to freeze or raise errors. (For example, coloring a 25 by 25 block of cells with different font colors will cause errors.) Excel font sizes must be positive integers, and the maximum font size is 409. Only one of subscript and superscript can be active at a time. Turning on superscript in a cell set to subscript will turn off superscript, and vice versa.

4. Methods4. Methods4. Methods4. Methods

Cells also have some associated methods.

ClearClearClearClear

clear clears the contents of a cell. Cell("A1").clear() is equivalent to Cell("A1").value = ''.

is_emptyis_emptyis_emptyis_empty is_empty will return True if a cell is empty and False otherwise. e.g: Cell("A1").is_empty() will return True if A1 has nothing in it, and False otherwise.

Page 7: excel addon

7

OffsetOffsetOffsetOffset offset takes a (row, column) tuple, and returns the cell at the appropriate position. e.g: Cell("A2").offset(1,2) will return Cell("B4"). SubtractionSubtractionSubtractionSubtraction

You can subtract two cells to get the offset between them. Cell("B4") - Cell("A2") = (2,1) For any two cells x and y on the same sheet x.offset(y-x) == y returns True.

Printing & RepresentationPrinting & RepresentationPrinting & RepresentationPrinting & Representation

Printing a cell gives the cell's name and its sheet. repr returns the cell's name. e.g: print Cell("Sheet1","A2") will print "A2 on Sheet1". repr(Cell("A2")) and repr(Cell(2,1)) will return "A2". Set nameSet nameSet nameSet name set_name will create a named range in Excel containing the cell it's called on. If the named range already exists, it will be overwritten. e.g: Cell("A1").set_name("first_cell"), Cell("A1:A10").set_name("first_cell") will both create a named range called 'first_cell' containing A1.

5. Ordering5. Ordering5. Ordering5. Ordering

Cells are ordered lexicographically within a sheet by row and then by column. e.g: "A1" is the first cell. "x1" is less than "y2" for any x and y. "B5" is greater than "B3". Cells from different sheets will compare as unequal, and trying to order them (e.g. Cell("Sheet1", "A1") < Cell("Sheet2", "A2")) raises an exception.

Page 8: excel addon

8

6. Range Syntax6. Range Syntax6. Range Syntax6. Range Syntax

You can enter a range as you would in Excel, i.e. using the ":", ",", and " " (space) operators (the last two are union and intersection, respectively). You can use "^" for intersection instead of " " if you prefer. This accepts named ranges as well.

7. Active Cell7. Active Cell7. Active Cell7. Active Cell set_active will set the active cell to the cell the method is called on. This cell must be on the active sheet. e.g: Cell("B3").set_active() will set the active cell to B3. Cell("Sheet2", "B3").set_active() will set the active cell to B3 if Sheet2 is active, and raise an error otherwise. Active Cell FunctionsActive Cell FunctionsActive Cell FunctionsActive Cell Functions The active_cell function gets and sets the active cell. This is a general function, not a method of Cell. Calling active_cell with no argument will return the active cell, while calling it with a cell or with arguements which can instantiate a cell (such as two integers, a tuple, or an Excel range) will set the active cell to that cell. e.g: active_cell() will return Cell("A1") when you first open a workbook. active_cell(Cell("A1")), active_cell("A1"), active_cell(1,1), and active_cell("A1:B5") will all set the active cell to A1.

8. Unicod8. Unicod8. Unicod8. Unicodeeee

If you read a cell with unicode characters into the Python shell, the characters will be returned as codepoints (e.g: "u'\u671d\u540d'). To display these characters, you have to print the value. The characters will print properly if you're using a version of Windows that supports the language the characters are in.

Page 9: excel addon

9

CellRangeCellRangeCellRangeCellRange The "CellRange" class is a container for cells. Cells in a CellRange must be on a single sheet. Cells are stored in order and without duplication.

1. Instantiation1. Instantiation1. Instantiation1. Instantiation You can create a CellRange the same way you create a Cell:

1. With a (row, column) pair or tuple.

e.g: CellRange(2,1) and CellRange((2,1)) return the CellRange containing "A2",

which we'll refer to as ["A2"].

2. By entering a range. This will return all the cells in the range.

e.g: CellRange("A2") returns ["A2"].

e.g: CellRange("A2:A10^A3:B5,A4,C3") returns ["A3","A4","A5","C3"].

3. By entering a named range. This will return the range. Named ranges must be

on the sheet passed to CellRange (or the active sheet).

e.g: CellRange("Use_VBA") will return ["NOT1993","NOT1994","NOT1995"] if

"Use_VBA" is the range "NOT1993:NOT1995".

There are also two ways to create a CellRange that don't have analogues for Cells:

1. With two (row, column) pairs or tuples. This returns the range with top left

corner given by the first pair and bottom right corner given by the second.

e.g: CellRange((2,1),(3,4)) and CellRange(2,1,3,4) return

["A2","B2","C2","D2","A3","B3","C3","D3"].

2. With a list of (row, column) tuples. This returns the cells given by the list.

e.g: CellRange([(1,1),(2,2),(3,3),(4,4),(5,5)]) returns ["A1","B2","C3","D4","E5"].

2. Properties2. Properties2. Properties2. Properties

Like Cell, CellRange has sheet and name properties. These are set when the CellRange is created and should not be changed. sheet contains the sheet of all of the cells in the CellRange. name is set to the string that was used to initialize it. If it was initialized with two tuples or four integers, the name will be generated using a colon. e.g: CellRange("A1:B5").name and CellRange((1,1),(5,2)).name will return "A1:B5", while

CellRange("A1,B1,A2:B5").name returns "A1,B1,A2:B5".

Page 10: excel addon

10

Printing & RepresentationPrinting & RepresentationPrinting & RepresentationPrinting & Representation

Printing a CellRange gives its name and its sheet. repr returns a comma separated string of all the cells in the CellRange. e.g: print CellRange("A1:B5") and print CellRange((1,1),(5,2)) will print "A1:B5 on Sheet1", while print CellRange("A1,B1,A2:B5") will print "A1,B1,A2:B5 on Sheet1" if the CellRanges are on Sheet1. Both repr(CellRange("A1:B5")) and repr(CellRange("A1,B1,A2:B5")) will return "A1, B1, A2, B2, A3, B3, A4, B4, A5, B5". Container propertiesContainer propertiesContainer propertiesContainer properties

CellRange has the properties of a standard container. Specifically, len and iter work as in regular containers, and you can access individual cells using list notation. e.g: len(CellRange("A1:B5")) returns 10. for cell in CellRange("A1:E5"): cell.value = cell.row * cell.col will set "A1" to 1, "B1" to 2, "D3" to 12, etc.

CellRange("A1:B5")[2] will return the cell "A2".

positionpositionpositionposition position returns the positions of all the cells in the range in a list. e.g: CellRange("B1:C2").position returns [(1,2),(1,3),(2,2),(2,3)]. Value & FormulaValue & FormulaValue & FormulaValue & Formula

Like Cell, CellRange has value and formula properties. CellRange("A1:B5").value is shorthand for [cell.value for cell in CellRange("A1:B5")]. You can set CellRange.value to a single value or to a list with the same length as the CellRange. Passing a single value will set all the cells in the CellRange to that value. e.g: CellRange("A1:B5").value = 5 will set the values of cells "A1" through "E5" to 5. CellRange("A1:B5").value = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] will set "A1" to 0, "B1" to 1, "A2" to 2, etc.

Page 11: excel addon

11

CellRange("A1:B5").value will return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] after the previous command. Getting and setting formulas works in the same way. CellRange.formula will accept both formulas and values. This enables copying over data from one range to another, including formulas. Formulas are copied directly, not relatively. e.g: CellRange("B1:B5").formula = "=A1" will set cells "B1" through "B5" to the value of "A1". CellRange("B1:B5").formula will return ["=A1","=A1","=A1","=A1","=A1"] after the previous command. CellRange("B1:B20").formula = CellRange("A1:A20").formula will copy the formulas in cells A1 through A20 to cells B1 through B20. If any of the cells contain data (instead of formulas), they'll be copied as well. Formulas are copied directly, so if A20 contains the formula "=SUM(A1:A19)", then B20 will also have the formula "=SUM(A1:A19)". This also works for date.

FormattingFormattingFormattingFormatting

Formatting works analogously to getting and setting values. You can set any of the cell formatting properties using a CellRange by passing that property a list of length one, or of the same length as the range. You can check the format of the range by returning a property, or by printing font. e.g: CellRange("A1:E5").font.bold = True will bold the text in cells A1 through E5. CellRange("A1:A10").font.bold = [True, False] * 5 will bold the text of every other cell in A1 through A10. If A1 through A10 have not had any other formatting changes, after this command print CellRange("A1:A10").font will print A1 has font color black, font size 11, bold A2 has font color black, font size 11 A3 has font color black, font size 11, bold A4 has font color black, font size 11 A5 has font color black, font size 11, bold A6 has font color black, font size 11 A7 has font color black, font size 11, bold

Page 12: excel addon

12

A8 has font color black, font size 11 A9 has font color black, font size 11, bold A10 has font color black, font size 11 Comments & AlignmentComments & AlignmentComments & AlignmentComments & Alignment Comment and alignment are passed through to the cells in a CellRange, just like values and formulas

3. Methods3. Methods3. Methods3. Methods

ConcatenateConcatenateConcatenateConcatenate

You can concatenate two CellRanges from the same sheet by adding them. Attempting to add two CellRanges from different sheets will raise an exception. The name of the new CellRange will consist of the names of the two CellRanges added together with a comma between them. e.g: CellRange("A1:A10") + CellRange("B1:B10") will return CellRange("A1:A10,B1:B10"). Set nameSet nameSet nameSet name set_name will create a named range in Excel containing the CellRange. If a named range of the that name already exists, it will be overwritten. e.g: CellRange("A1, B2, C3, D4, E5").set_name("diagonal") will create a named range called 'diagonal' containing the cells A1, B2, C3, D4 and E5.

isisisis empty empty empty empty is_empty will return True if the range is empty and False otherwise. e.g: CellRange("A1:A10").is_empty() will return True if A1 through A10 are all empty, and False otherwise.

Modifying CellRangesModifying CellRangesModifying CellRangesModifying CellRanges

You can append, delete and set cells in CellRanges. append

Page 13: excel addon

13

You can append a Cell to a CellRange if both are on the same sheet. The name of the Cell will be added to the name of the CellRange. If the Cell is already in the CellRange, the command will have no effect. e.g: CellRange("A1:E5").append(Cell("F5")) will return CellRange("A1:E5,F5"). CellRange("A1:E5").append(Cell("C3")) will return CellRange("A1:E5"). delete

Deleting a cell will remove it from the CellRange. The name of the CellRange will change to the representation of the new CellRange. e.g: del CellRange("A1:B2")[1] will set the CellRange to CellRange("A1,A2,B2"). set

Setting a cell in a CellRange is equivalent to deleting the Cell you are changing, and then appending the new cell. e.g. CellRange("A1:E5")[2] = Cell(16,25) is the same as x = CellRange("A1:E5") del x[2] x.append(Cell(16,25))

ComparisonsComparisonsComparisonsComparisons

Two CellRanges are considered equal if they contain the same cells on the same sheet. They may have different names. CellRanges are unordered. e.g: CellRange("Sheet1","A1:B5") == CellRange("Sheet1","A1:A5,B1:B5") will return True.

ClearClearClearClear

Like a Cell, you can use clear() to clear all the values in a CellRange. e.g: CellRange("A1:E5").clear() will clear cells A1, A2, ... E5.

Page 14: excel addon

14

Worksheets Worksheets Worksheets Worksheets

1. Active Sheet1. Active Sheet1. Active Sheet1. Active Sheet

When you create a new Cell or CellRange without specifying a sheet argument, it will be placed on the active sheet. The default active sheet is the one that is visible in Excel when you run a script or open a Python shell. The active_sheet function interacts with the active sheet. Calling active_sheet without an argument will return the active sheet, and calling it with a sheet name will set the active sheet. e.g: If Sheet1 is active, active_sheet() will return "Sheet1". active_sheet("Sheet2") will set the active sheet to Sheet2.

2. Display Sheet2. Display Sheet2. Display Sheet2. Display Sheet

The display sheet is the visible sheet in Excel. The display_sheet function interacts with the display sheet. Calling display_sheet without an argument will return the display sheet, and calling it with a sheet name will set the display sheet. e.g: If Sheet1 is displayed, display_sheet() will return "Sheet1". display_sheet("Sheet2") will display Sheet2.

3. Clear/Delete row/column3. Clear/Delete row/column3. Clear/Delete row/column3. Clear/Delete row/column

The functions clear_row, clear_col, del_row, and del_col will clear or delete a row or column. Rows are specified by number, and columns can be specified by number or letter. You can also pass a cell, which will result in the row or column of that cell being cleared or deleted, or a CellRange, list, or tuple of rows or columns, which will clear or delete all the rows/columns in the CellRange or the list or tuple.

Page 15: excel addon

15

You can pass a sheet name as the second argument to specify which a sheet; otherwise the function will interact with the active sheet. e.g: clear_row(1) and clear_row(Cell("A1")) will clear the first row. del_col(3), del_col("C"), and del_col(Cell(3,3)) will delete the third column. clear_col([1, 2, 3], "Sheet2") and clear_col(CellRange("A1:C1"), "Sheet2") will clear the first three columns on Sheet2. Note:Note:Note:Note: calling del_row([1, 2]) is not the same as calling del_row(1) and then del_row(2). del_row([1,2]) will delete the first two rows, while del_row(1) will delete the first row, which will shift all rows in the spreadsheet. del_row(2) will then delete the new second row; this was originally the third row, so this is equivalent to calling del_row([1,3]).

4. Insert row/column4. Insert row/column4. Insert row/column4. Insert row/column insert_row and insert_col insert rows and columns, respectively. They take the same input as clear_row and clear_col, and will insert a row above the row passed (or a column before the column passed). e.g: insert_row(1) and insert_row(Cell("A1")) will insert a new first row. insert_col(3), insert_col("C"), and insert_col(Cell(3,3)) will insert a new third column. insert_col([1, 2, 3], "Sheet2") will insert columns before columns 'A', 'B' and 'C'. (The result is new_col, A, new_col, B, new_col, C...)

5. Sheet functions5. Sheet functions5. Sheet functions5. Sheet functions

AutofitAutofitAutofitAutofit

The autofit command resizes sheet cells. It will resize the active sheet unless passed a sheet name. You can pass a range as the second argument, to resize the columns in that range. e.g: autofit() will resize the current sheet. autofit('sheet2') will resize Sheet2. autofit('sheet1', 'A1:E5') will resize columns A through E to match the widest cells in rows 1 through 5 on Sheet1.

Page 16: excel addon

16

Clear SheetClear SheetClear SheetClear Sheet clear_sheet clears the named sheet. If called with no argument, clears the active sheet. e.g: clear_sheet("Sheet2") will clear sheet 2.

All SheetsAll SheetsAll SheetsAll Sheets

To return a list of all sheets in the workbook, use the all_sheets function. e.g: all_sheets() returns ['Sheet1', 'Sheet2', 'Sheet3'] on a default workbook.

New SheetNew SheetNew SheetNew Sheet new_sheet creates a new sheet. The sheet can't have the same name as an existing sheet. If called with no arguments, will create the next numbered sheet. e.g: new_sheet("Data") will create a sheet named "Data". new_sheet() will create "Sheet5" in a new workbook.

Remove SheetRemove SheetRemove SheetRemove Sheet remove_sheet removes a sheet. You can't remove the last sheet in a workbook.

Rename SheetRename SheetRename SheetRename Sheet rename_sheet renames a sheet. The new name cannot be the name of an existing sheet. e.g: rename_sheet("Sheet1","Sheet_over_9000") will rename Sheet1 to Sheet_over_9000. Note:Note:Note:Note: After installing DataNitro, Excel will be missing Sheet4. If you add additional sheets after the default 3, they'll start with Sheet5.

6. Merging Cells6. Merging Cells6. Merging Cells6. Merging Cells merge_cells(start_cell, end_cell) will merge the cells in the box with top-left start_cell and bottom-right end_cell. start_cell and end_cell can be cells or cell

Page 17: excel addon

17

names. To use a sheet other than the active sheet, pass it as the optional third argument. e.g: merge_cells(Cell(1,1), Cell(5,5)) and merge_cells("A1", "E5") will merge the cells between A1 and E5. merge_cells(Cell(1,1),'A2','Sheet2') will merge A1 and A2 on Sheet2.

7. Pivot Tables7. Pivot Tables7. Pivot Tables7. Pivot Tables pivot_refresh(sheet) will refresh the pivot tables on sheet. If sheet isn't passed, it'll refresh the active sheet. e.g: pivot_refresh() will refresh the pivot tables on the active sheet, and pivot_refresh('Table') will refresh the pivot tables on sheet Table.

8. Saving8. Saving8. Saving8. Saving

You can save the workbook by calling save(). You can also save the file under a different name by calling save with a filename, e.g. save("DataNitro"), or save a copy of the current file by calling save_copy with a filename, e.g. save_copy("DataNitro"). Both save with a filename and save_copy will save to your Documents directory if not provided with a filepath.

Page 18: excel addon

18

User Defined FunctionsUser Defined FunctionsUser Defined FunctionsUser Defined Functions User defined functions, or udf's, are Python functions that can be called directly from Excel.

1. Overview1. Overview1. Overview1. Overview

To import Python functions, define them in a file named "functions.py" and import that file into DataNitro. Any function defined in the file will then be available for use in Excel. It's not necessary to run the script. Imported functions cannot make calls to other Excel objects (so they cannot use Cell or CellRange objects, for example). To use values in other cells, pass them as arguments to the function. e.g: To compute the sum of cells A1 and A2, write the following in functions.py: def my_sum(x, y): return x + y You can then put =my_sum(A1, A2) into a cell. The following function will fail, however: def my_sum_a1_a2(): return Cell(A1).value + Cell(A2).value

2. Input and Output2. Input and Output2. Input and Output2. Input and Output

Function InputFunction InputFunction InputFunction Input

Imported functions must have a fixed number of arguments. Functions with optional parameters, args, or kwargs will not work. Each input must be a single cell (not a range).

Page 19: excel addon

19

Function OutputFunction OutputFunction OutputFunction Output

The udf will print the return value in the cell it is called. If an error occurs, it will print the error to the cell.

3. Notes3. Notes3. Notes3. Notes

If you have multiple instances of Excel open, udf's will only work in the first one.

Page 20: excel addon

20

VBA VBA VBA VBA

1. Calling VBA from DataNitro1. Calling VBA from DataNitro1. Calling VBA from DataNitro1. Calling VBA from DataNitro

You can call VBA subroutines and functions with the VBA command. These docs refer to both subroutines and functions as macros. VBA takes these inputs: VBA(macro_name, args, target_sheet) macro_name is the macro's name as a string, including the module or sheet it was

defined in. (This uses a sheet's codename.)

args is an optional list of arguments for the macro. A macro can take up to 30

arguments.

target_sheet is an optional argument specifying the sheet the macro executes against. If

you don't list a target sheet, it'll execute on the active sheet. This uses the sheet's

name, not its codename.

See the bottom of this page for the difference between a sheet's name and codename.

SubroutinesSubroutinesSubroutinesSubroutines

Subroutines can be defined in a sheet or in a module. If a subroutine is defined in a module, you don't have to specify which module its defined in unless there's another macro with the same name defined in a different module. If the subroutine "test" is defined in Module1, VBA("test") VBA("Module1.test") will both execute "test" against the active sheet, and VBA("Module1.test", [ ], "Sheet1") will execute it against "Sheet1".

If a subroutine is defined in a sheet, you need to specify which sheet its defined in.

You also can't specify a target sheet; it will always execute against the sheet its

Page 21: excel addon

21

defined in.

If "test" is defined in "Sheet1", VBA("Sheet1.test") VBA("Sheet1.test", [ ], "Sheet2") will both run the subroutine against Sheet1, while VBA("test") will fail.

Subroutines don't return a value.

FunctionsFunctionsFunctionsFunctions

Functions are called in the same way as subroutines. VBA functions must be defined in a module, not in a sheet, to work properly. Functions return a value to DataNitro. For example, if this function defined in Module1: Function TimesThree(x) TimesThree = x * 3 End Function You can call it from DataNitro: >>>VBA("Module1.TimesThree", [2]) 6 >>>VBA("TimesThree", [4]) 12

2. Calling DataNitro from VBA2. Calling DataNitro from VBA2. Calling DataNitro from VBA2. Calling DataNitro from VBA

Calling ScriptsCalling ScriptsCalling ScriptsCalling Scripts

You can call a DataNitro script from VBA with this line: Sub call_DN() Application.COMAddIns("DataNitro.DataNitro").Object.RunScript ("test.py") End Sub Replace "test.py" with the name of your imported script. If you have multiple scripts

with the same filename, you should use the same name that the script has in the

DataNitro toolbar, e.g. "test.py (1)".

Page 22: excel addon

22

Calling UserCalling UserCalling UserCalling User----Defined FunctionsDefined FunctionsDefined FunctionsDefined Functions

There are two ways to call DataNitro UDF's from VBA. If you want to call a UDF inside a cell, the best way is to write the formula directly to the cell. For example, if this functions.py file is imported into DataNitro: def f(x): return 3*x you can call f from the active cell like this: ActiveCell.value = "=f(3)" or this: ActiveCell.value = "=f(A1)" If you want to use a DataNitro UDF inside VBA, you need to run it. To store the

value of the UDF in x, we do this: x = Application.Run("f", 3) or this: x = Application.Run("f", Cells(1, 1).value) Application.Run takes the function name, as a string, followed by up to 30 arguments as

input.

3. Sheets: name 3. Sheets: name 3. Sheets: name 3. Sheets: name and codenameand codenameand codenameand codename

Each Excel sheet has a name and a codename. The sheet's name is displayed in Excel and can be changed by the user, as well as through DataNitro. The codename is generally inaccessible by the user, except through VBA; DataNitro never interacts with it unless you're working with VBA. In the VBA editor, the properties tab lists the name as name, and the codename as (name). For example, if you have a sheet with the name "James Bond" and the codename "Double07", it'll be listed in Excel as "James Bond". You can write to it from DataNitro by calling Cell("James Bond", "A1").value = 3 but Cell("Double07", "A1").value = 3 will give an error.

In VBA, this will work: Sheets("James Bond").Cells(1, 1).Value = "Do you expect"

Page 23: excel addon

23

Double07.Cells(2, 1).Value = "me to talk?" and both of these will not: Sheets("Double07").Cells(1, 1).Value = "No, Mr. Bond, I" James Bond.Cells(2, 1).Value = "expect you to..." If the subroutine "DrNo" is defined in the sheet, you can call it with from DataNitro

with VBA("Double07.DrNo") but VBA("James Bond.DrNo") will fail.

If the subroutine "Goldfinger" is defined in Module1, and you want to run it against

the sheet, VBA("Goldfinger", [ ], "James Bond") will work, but VBA("Goldfinger", [ ], "Double07") will fail.