Autoit команды для excel
Просто оставлю это здесь, вдруг кому пригодится. На форуме не нашёл подобного.
Скрипт сохраняется в блокнот с расширением .au3 (файл AutoIt) и исполняется соответственно. Или можно скомпилировать.
Имя макроса для запуска и адрес файла поменяйте на свои.
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
[/vba]
Пока в фоновом режиме ломаю голову, как прилепить это на горячую клавишу. Возможно, политика безопасности компании на работе не позволяет. Дома как-нибудь проверю вариант.
; capture and pass along a keypress
HotKeySet("!x", "Open_File")
HotKeySet("!z", "End_Script")
While 1
sleep (50)
WEnd
Func Open_File()
HotKeySet("!x")
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
EndFunc
Func End_Script()
HotKeySet("!z")
Exit
EndFunc
Просто оставлю это здесь, вдруг кому пригодится. На форуме не нашёл подобного.
Скрипт сохраняется в блокнот с расширением .au3 (файл AutoIt) и исполняется соответственно. Или можно скомпилировать.
Имя макроса для запуска и адрес файла поменяйте на свои.
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
[/vba]
Пока в фоновом режиме ломаю голову, как прилепить это на горячую клавишу. Возможно, политика безопасности компании на работе не позволяет. Дома как-нибудь проверю вариант.
; capture and pass along a keypress
HotKeySet("!x", "Open_File")
HotKeySet("!z", "End_Script")
While 1
sleep (50)
WEnd
Func Open_File()
HotKeySet("!x")
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
EndFunc
Func End_Script()
HotKeySet("!z")
Exit
EndFunc
Просто оставлю это здесь, вдруг кому пригодится. На форуме не нашёл подобного.
Скрипт сохраняется в блокнот с расширением .au3 (файл AutoIt) и исполняется соответственно. Или можно скомпилировать.
Имя макроса для запуска и адрес файла поменяйте на свои.
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
[/vba]
Пока в фоновом режиме ломаю голову, как прилепить это на горячую клавишу. Возможно, политика безопасности компании на работе не позволяет. Дома как-нибудь проверю вариант.
; capture and pass along a keypress
HotKeySet("!x", "Open_File")
HotKeySet("!z", "End_Script")
While 1
sleep (50)
WEnd
Func Open_File()
HotKeySet("!x")
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
EndFunc
Func End_Script()
HotKeySet("!z")
Exit
EndFunc
Hugo, привет. Значит ли комментарий выше, что у тебя получилось запустить код из-под спойлера? Rioran
Привет. Отработало, только что попробовал, но то что не под спойлером. Только конечно подставил свой файл с моим макросом.
P.S. И спойлер тоже отработал.
Привет. Отработало, только что попробовал, но то что не под спойлером. Только конечно подставил свой файл с моим макросом.
P.S. И спойлер тоже отработал. Hugo
Hugo, классно, спасибо. На счёт "без спойлера" сомнений не было, код "отшлифован" хорошенько =) Вопрос был только к спойлеру. Значит, дело не в коде, какой-то вопрос на моей стороне не даёт горячей клавише сработать. Позже надо потестировать пару вариантов.
Hugo, классно, спасибо. На счёт "без спойлера" сомнений не было, код "отшлифован" хорошенько =) Вопрос был только к спойлеру. Значит, дело не в коде, какой-то вопрос на моей стороне не даёт горячей клавише сработать. Позже надо потестировать пару вариантов. Rioran
То что под спойлером после запуска висит в трее и ждёт пока не нажмёте Alt+x или Alt+z. Один цикл, т.е. затем скрипт нужно запускать заново.
То что под спойлером после запуска висит в трее и ждёт пока не нажмёте Alt+x или Alt+z. Один цикл, т.е. затем скрипт нужно запускать заново. Hugo
Hugo, лечится добавлением одной строки:
; capture and pass along a keypress
HotKeySet("!x", "Open_File")
HotKeySet("!z", "End_Script")
While 1
sleep (50)
WEnd
Func Open_File()
HotKeySet("!x")
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
HotKeySet("!x", "Open_File") ;'Вот эту добавляем - и теперь жать можно многократно.
EndFunc
Func End_Script()
HotKeySet("!z")
Exit
EndFunc
[/vba]
Если кому-то надо, могу ещё прикрутить быструю клавишу для закрытия файла. Или что бы макрос проигрывался и файл закрывался сам с сохранением / без.
Альт-Икс запускает открытие файла и работу макроса, Альт-Зет прерывает скрипт полностью, чтобы быстрые клавиши не занимать.
Hugo, лечится добавлением одной строки:
; capture and pass along a keypress
HotKeySet("!x", "Open_File")
HotKeySet("!z", "End_Script")
While 1
sleep (50)
WEnd
Func Open_File()
HotKeySet("!x")
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
HotKeySet("!x", "Open_File") ;'Вот эту добавляем - и теперь жать можно многократно.
EndFunc
Func End_Script()
HotKeySet("!z")
Exit
EndFunc
[/vba]
Если кому-то надо, могу ещё прикрутить быструю клавишу для закрытия файла. Или что бы макрос проигрывался и файл закрывался сам с сохранением / без.
Альт-Икс запускает открытие файла и работу макроса, Альт-Зет прерывает скрипт полностью, чтобы быстрые клавиши не занимать. Rioran
; capture and pass along a keypress
HotKeySet("!x", "Open_File")
HotKeySet("!z", "End_Script")
While 1
sleep (50)
WEnd
Func Open_File()
HotKeySet("!x")
$Excel_App = ObjCreate("Excel.Application") ; Create an Excel Object
$Excel_App.Workbooks.Open ("C:\Users\rvoronov\Desktop\Electricity_Question_02.xlsb")
Sleep(1000)
$Excel_App.Visible = 1 ; Let Excel show itself
$Excel_File = $Excel_App.ActiveWorkbook.Name
Sleep(1000)
$Excel_Macro = "Rio_Test"
Sleep(1000)
$Excel_App.run ("'" & $Excel_File & "'!" & $Excel_Macro)
HotKeySet("!x", "Open_File") ;'Вот эту добавляем - и теперь жать можно многократно.
EndFunc
Func End_Script()
HotKeySet("!z")
Exit
EndFunc
[/vba]
Если кому-то надо, могу ещё прикрутить быструю клавишу для закрытия файла. Или что бы макрос проигрывался и файл закрывался сам с сохранением / без.
Альт-Икс запускает открытие файла и работу макроса, Альт-Зет прерывает скрипт полностью, чтобы быстрые клавиши не занимать. Автор - Rioran
Дата добавления - 20.03.2015 в 15:54
Возвращает значение целевой ячейки активного рабочего листа открытой рабочей книги Excel.
$oExcel | Ссылка на COM-объект "Excel.Application" полученная ранее вызванными _ExcelBookOpen () , _ExcelBookNew () , или _ExcelBookAttach () |
$sRangeOrRow | Адрес ячейки в формате A1, или номер целевой строки - в случае если адрес целевой ячейки указывается в формате R1C1(номер строки\номер столбца) |
$iColumn | [необязательный] Номер столбца, если адрес целевой ячейки указывается в формате R1C1(номер строки\номер столбца) (по умолчанию = 1) |
Успех: | Возвращает значение целевой ячейки |
Ошибка: | Возвращает 0, Устанавливает значение флага ошибки @error : |
@error : | 0 - Скрипт завершил работу без ошибок |
1 - Ошибка OLE/COM ( $oExcel ), возможно указанный объект не существует | |
2 - Значение параметра не является числом, или недопустимо | |
@extended : | 0 - Ошибка в значении строки ( $sRangeOrRow ) |
1 - Ошибка в значении столбца ( $iColumn ) |
Эта функция возвращает значение одной ячейки за один вызов.
Получить значения из диапазона ячеек можно при помощи _ExcelReadArray
-------------------------------------------------------------------------
Внимание. документы разных форматов MS Office имеют различные ограничения по количеству столбцов и строк:
*.xls (формат xlExcel8, стандартный для MS Office 2003,97,95) имеет ограничения в 255 столбцов 65 535 строк
*.xlsx,*.xlsb,*.xlsm (XML-форматы MS Office 2007-2010) имеют ограничения в 16 384 столбца и 1 048 576 строк
Local $oExcel = _ExcelBookNew () ; Создаем новую рабочую книгу
_ExcelWriteCell ( $oExcel , "Строка записана скриптом AutoIt" , 1 , 1 ) ; Записываем данные в ячейку
$sCellValue = _ExcelReadCell ( $oExcel , 1 , 1 ) ; Читаем данные из ячейки
MsgBox ( 4096 , "" , "Значение ячейки: " & @CRLF & '"' & $sCellValue & '"' )
MsgBox ( 4096 , "_ExcelReadCell | Пример 1" , "Демонстрация завершена, нажмите ОК" )
_ExcelBookSaveAs ( $oExcel , @TempDir & "\Temp.xls" , "xls" , 0 , 1 ) ; Сохраняем файл в директории временных файлов, перезаписывая если необходимо.
_ExcelBookClose ( $oExcel ) ; Закрываем рабочую книгу
Local $oExcel = _ExcelBookNew () ; Создаем новую рабочую книгу
For $i = 1 To 5
_ExcelWriteCell ( $oExcel , $i , $i , 1 ) ; Записываем данные в ячейку
Next
;Циклически используем метод _ExcelReadCell, и отображаем в окне возвращаемое им значение на каждом шаге цикла
For $i = 1 To 5
$sCellValue = _ExcelReadCell ( $oExcel , $i , 1 )
MsgBox ( 4096 , "" , "Значение ячейки " & "A" & $i & ":" & @CRLF & $sCellValue , 2 )
Next
MsgBox ( 4096 , "_ExcelReadCell | Пример 2" , "Демонстрация завершена, нажмите ОК" )
_ExcelBookSaveAs ( $oExcel , @TempDir & "\Temp.xls" , "xls" , 0 , 1 ) ; Сохраняем файл в директории временных файлов, перезаписывая если необходимо.
_ExcelBookClose ( $oExcel ) ; Закрываем рабочую книгу
Всем привет. Я новенький, хочу использовать Autoit для своей работы, после долгих поисков понял, что она поможет мне автоматизировать рутину и сократить время выполнения всех моих операций по меньшей мере в 10 раз. Единственный нюанс, мне дико сложно изучать всё самостоятельно. Не ругайтесь на банальные вопросы, все мы когда то с чего то начинаем.
Решил написать первую программу, весьма лёгкую, но для начала мне нужно научиться полностью работать с Excel-м, версия проги у меня последняя, но что бы работать с Excel видимо нужен плагин Excel.au3, но я так и не нашёл где его скачать, был на оф сайте, там вроде регистрация нужна, не проходил её, но если пнёте туда, то буду, плюс я не нашёл ни одного русского справочника по всем функциям и работой с Excel.au3. Ребят, помогите что ли, а то как то сложновато вникнуть сразу с нуля :stars:
Спасибо.
Alofa
Гость
А качать и не надо, она у вас уже и так находится в папке . \AutoIt3\Include.
При создании нового скрипта библиотеку Excel.au3 нужно просто подключить.
По видимому и не искали вовсе:
- Онлайн Справка;
- Оффлайн Справка.
. или же просто не понимаете принцип работы.
fergios
Новичок
А качать и не надо, она у вас уже и так находится в папке . \AutoIt3\Include.
При создании нового скрипта библиотеку Excel.au3 нужно просто подключить.
fergios
Новичок
Не было времени работать с программой. Сегодня решил начать и сразу же ступарнул. Дело в том, что бы мне научиться поэтапно писать для своих целей программы мне нужно научиться полностью изучить функции которые мне для них потребуются. Начал с экселя. Проблема следующая - хочу ввести в ячейки данные вручную после чего их скопировать в блокнот в столбик, а потом попробовать наоборот инфу перегнать с блокнота в эксель. У меня версия v3.3.14.2 и в ней нету видимо функции _ExcelWriteCell.
Позвольте спросить у знающих:
1) Функция, которая копирует заданную ячейку.
2) Функция, которая удаляет строку.
3) Как вот например реализовать такую вот штуку - дата например 25.11.2015 15:52:43 это мне нужно будет в две разных формы вставлять по отдельности, вот к времени прибавить пол часа, например сейчас 15:52:43, а надо вставить +30 мин 16:22:43?
4) Есть ли какая либо проверка, когда заканчиваются строки, мне надо что бы скрипт делал накладные до того момента, пока есть данные в экселе, количество данных всегда меняется, поэтому хотелось бы что бы он сам фурычил, у меня была как бы идея, мол перед началом выполнения через функцию в экселе считать сколько строк переносить в SAP, а потом это считывать и уже там пошло или просто есть в экселе функция которая считает, а у меня перед началом скрипт спрашивает сколько раз впахиваем на дядю)
Блин, знаю что всё тупо, но что бы разогнаться, нужна конечно же помощь, поэтому простите за вопросы тупые.
AutoIT Гуру
Откройте файл "Excel.au3", который по умолчанию находится в "C:\Program Files\AutoIt3\Include", в нём вы увидите название всех функций, которые отличаются от старых. К сожалению по новым функциям русской справки нет,но есть масса примеров. По вопросам :
1 -
The Excel UDF offers functions to control and manipulate Microsoft Excel workbooks.
This page describes the Excel UDF that comes with AutoIt 3.3.12.0 or later.
Contents
Features
New versions of Microsoft Office have been released since the last changes were made to the Excel UDF. The new extensions (e.g. xlsx) were not (fully) supported, new functions were missing etc. The current version of the Excel UDF lifts this limitations.
- Works with as many instances of Excel as you like - not just one
- Works with any Workbook - not just the active one
- Works with any Worksheet - not just the active one
- Only does what you tell it to do - no implicit "actions"
- Only one function to read from a cell or a range
- Only one function to write a string, a 1D or 2D array to a cell or a range
- Support for every file format Excel supports
- Speed enhancements when transferring data from/to an Excel sheet (20 - 100 times faster)
Concepts
The Areas collection contains one Range object for each discrete, contiguous range of cells within the selection.
Range
A Range is a rectangular block made of one or more cells that Excel treats as a unit. The functions of the UDF mainly work with ranges. A range - unlike a selection - is not visible on the screen.
Examples how to define special ranges can be found here.
Cell reference
The UDF only supports the A1 form (example: "B7") to reference cells. The R1C1 form (example "R7C2") is not supported. But the UDF provides functions to translate a cell reference between this two forms.
You can reference cells by name as well.
Examples
- Single cell: "B7"
- Multiple cells: "A1:B7"
- Row(s): "2" or "3:5"
- Column(s): "B" or "D:F"
- Name: "TestRange"
Filter
The Excel Autofilter allows you to view specific rows in an Excel spreadsheet, while hiding the other rows in the worksheet based on various criteria.
Details and example scripts how to work with filters can be found here.
Date and Time
Excel stores date and time as a number representing the number of days since 1900-Jan-0, plus a fractional portion of a 24 hour day: ddddd.tttttt .
This is called serial date-time.
When you enter a time without a date value (e.g. 15:00) the date portion is a zero. This indicates that there is no date associated with the time and does not automatically put in the current date.
The integer portion of the number represents the number of days since 1900-Jan-0. For example, the date 19-Jan-2000 is stored as 36,544.
Actually, this number is one greater than the actual number of days. Why can be found here.
The fractional portion of the number represents the fractional portion of a 24 hour day. For example, 6:00 AM is stored as 0.25,
Example script (written by AutoBert) to convert serial date-time to a readable format:
Features not covered by the UDF
The UDF only covers basic user needs. Single line functions (like switching to another sheet) or functions with too many parameters (like formatting a cell or range) are not covered by this UDF. You need to use the Excel COM yourself.
I will give a few examples here. The rest can be found on MSDN.
Format a range
Alignment
Background
Sets the background to yellow:
Borders
Bold etc.
True if the font is bold. Read/write.
This works similar for Italic, Strikethrough, Subscript, Superscript and Underline.
Color, ColorIndex
Color: Returns or sets the primary color of the object. Use the RGB calculation below to create a color value.
ColorIndex: Returns or sets a variant value that represents the color of the font. The color is specified as an index value into the current color palette.
Object | Color |
---|---|
Border | The color of the border. |
Borders | The color of all four borders of a range. If they're not all the same color, Color returns 0 (zero). |
Font | The color of the font. |
Interior | The cell shading color or the drawing object fill color. |
Tab | The color of the tab. |
Returns or sets a variant value that represents the name of the font.
Returns or sets the size of the font specified in units of points.
Underline
Returns or sets the type of underline applied to the font. Can be one of the XlUnderlineStyle constants xlUnderlineStyleNone, xlUnderlineStyleSingle, xlUnderlineStyleDouble, xlUnderlineStyleSingleAccounting or xlUnderlineStyleDoubleAccounting. Read/write.
Height/Width
Property | Description |
---|---|
ColumnWidth | Returns or sets the width of all columns in the specified range. If columns in the range have different widths, this property returns null. |
One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used.
Number, Date/Time Format
Returns or sets a variant value that represents the format code for the object.
This property returns Null if all cells in the specified range don't have the same number format.
The format code is the same string as the Format Codes option in the Format Cells dialog box. The Format function uses different format code strings than do the NumberFormat and NumberFormatLocal properties.
A number format consists of up to 4 items, separated by semicolons. Each of the items is an individual number format. The first by default applies to positive numbers, the second to negative numbers, the third to zeros, and the fourth to text.
A very good description of format codes for numbers, date/time etc. can be found here.
Available colors are [Black], [Blue], [Cyan], [Green], [Magenta], [Red], [White], and [Yellow].
Format a window
Freeze panes
Freezes the first column and first row:
Script breaking changes after AutoIt version 3.3.10.2
New versions of Microsoft Office have been released since the last changes were made to the Excel UDF. New file types and new functions needed to be supported, hence the UDF was complete rewritten.
Some functions/parameters have been removed or renamed, new functions/parameters have been added. A detailed list of changes can be found here.
General
All function names have been changed from _Excel* to _Excel_*.
@extended no longer contains the number of the invalid parameter. The code returned in @error tells exactly what went wrong.
The following list shows the old/new function/parameter name (a "-" is shown if the function/parameter has been removed) and some example scripts how to mimic the behaviour of the "old" UDF. If there is no entry for a removed function/parameter then there is no need for this functionality.
Function -/_Excel_Open
It's mandatory now to call function _Excel_Open before any other function (except _Excel_BookAttach). This function didn't exist in the old UDF. @extended is set if Excel was already running.
Function _ExcelFontSetProperties/-
There are so many formatting functions in Excel that they can't be covered by a few functions. The function only contained a single line of code. So it was removed. Use the code examples above to format a range.
Function _ExcelHorizontalAlignSet/-
There are so many formatting functions in Excel that they can't be covered by a few functions. The function only contained a single line of code. So it was removed. Use the code examples above to format a range.
Function _ExcelSheetActivate/-
The function only contained a single line of code. So it was removed. Replace the function with the following code:
Function _ExcelSheetNameGet/-
The function only contained a single line of code. So it was removed. Replace the function with one of the following lines of code:
Function _ExcelSheetNameSet/-
The function only contained a single line of code. So it was removed. Replace the function with one of the following lines of code:
Compare example scripts
In this section I will show how some selected example scripts taken from AutoIt 3.3.8.1 should look like with the new Excel UDF.
To enhance readability error checking statements have been omitted.
But I highly recommend to check for errors after each call of a _Excel_* function.
Miscellaneous
Transpose limits
Version | Format | Max. rows | Max. columns | Transpose limit |
---|---|---|---|---|
Excel 2016 (16.0) | XLSX | 1.048.576 | 16.384 (XFD) | 65536 rows (according to the newtonexcelbach article above) |
Excel 2013 (15.0) | XLSX | 1.048.576 | 16.384 (XFD) | 65536 rows (according to the newtonexcelbach article above) |
Excel 2010 (14.0) | XLSX | 1.048.576 | 16.384 (XFD) | 65536 rows (tested by myself with an [65537][1] array) |
Excel 2007 (12.0) | XLSX | 1.048.576 | 16.384 (XFD) | (because Excel 2002 and Excel 2010 have the same limit) |
Excel 2003 (11.0) | XLS | 65.536 | 256 (IV) | (because Excel 2002 and Excel 2010 have the same limit) |
Excel 2002 (10.0) | XLS | 65.536 | 256 (IV) | 65536 rows (tested by kylomas with an [65537][2] array) |
Excel 2000 (9.0) | XLS | 65.536 | 256 (IV) | 5461 cells |
Excel 97 (8.0) | XLS | 65.536 | 256 (IV) | 5461 cells |
Excel 95 (7.0) | XLS | 16.384 | 256 (IV) | 5461 cells |
Excel 5.0 (1993) | XLS | 16.384 | 256 (IV) | |
Excel 4.0 (1992) | XLS | 16.384 | 256 (IV) | |
Excel 3.0 (1990) | XLS | 16.384 | 256 (IV) | |
Excel 2.0 (1987) | XLS | 16.384 | 256 (IV) | |
Excel 1.0 (1985) | XLS | 16.384 | 256 (IV) |
Furthermore the transpose method has a cell size limit of 255 chracters.
Depending on the Excel version you get or do not get an error for both limitations. When the transpose method fails use the internal _ArrayTranspose method by setting parameter $bForceFunc to True for functions _Excel_RangeRead and _ExcelRangeWrite. The function is limited by AutoIt's array limits only.
Script crashes
When your script processes a large amount of workbooks in a loop and suddenly crashes without error then try to run your script in 64 bit mode by adding
_Excel_RangeWrite writes no data
_Excel_RangeWrite does not write any data to a worksheet AND does not set @error. This can be caused by:
- a cell in the data to be written exceeds the 255 characters limit
- a cell containing data of type object
- a cell containing the keyword Null
You could use something like this to check the correctness of your data. Row, Column and explanation get written to the console.
Example for a 2D array:
Check if workbook is password protected
There seems to be no way to check if a workbook is password protected without opening it.
When you call _Excel_BookOpen without providing a password, a window pops up asking for the password if it is protected. This window can't be automated.
Call _Excel_BookOpen and provide a password (even a wrong one). If the workbook has no password on it, it will open with @error set to 0; if it does have a password it will not get opened and set @error to 3 and @extended to -2147352567.
Выкидываю программку которая позволяет сделать выборку условию "Заполнено" или "Незаполнено" ячейка 5го столбика и поместить данные всей строчки в отдельный xls файл.
+ Добавка к реестрам создает пункт в контекстном меню мышки.
HotKeySet("", "eExit")
Func eExit()
Exit 0
EndFunc
Opt("TrayIconDebug", 1)
Opt("WinTitleMatchMode", 2)
;путь к файлу
;~ $sFile = @ScriptDir & "\KALDE ОПТ 2012-03-05.xls"
;получаем путь файла из командной строки
If $CmdLine[0] = 0 Then Exit
$sFile = $CmdLine[1]
;открываем в скрытом режиме
$fVisible = 0
;только для чтения
$fReadOnly = true
;открыть книгу
Local $oExcel = _ExcelBookOpen($sFile, $fVisible, $fReadOnly)
;Номер последней строчки
$max_row = $oExcel.ActiveSheet.UsedRange.Rows.Count
;Прочитать колонку ячеек
Local $aArray1 = _ExcelReadArray($oExcel, 1, 5, $max_row, 1, 1)
;~ _ArrayDisplay($aArray1, "Vertical")
;столбец
$column = 5
;строка
$row = 1
;ПОИСКОВАЯ ЯЧЕЙКА
$search_cell = $oExcel.Activesheet.Cells($row, $column).Value
;~ $search_cell = _ExcelReadcell($row, $column)
;запись положительного результата поиска
Local $write_row_num[$max_row +1]
;последняя запись положительного результата
$last_row_num = 1
if $search_cell <> "" and $search_cell <> " ----" then
;запись положительного результата поиска
$write_row_num[$last_row_num] = $row
;переход к следущей ячейке для записи результата
$last_row_num = $last_row_num + 1
EndIf
;переход к следующей ячейке для поиска в столбце
$row = $row + 1
$search_cell = $oExcel.Activesheet.Cells($row, $column).Value
until $row = $max_row +1
;~ _ArrayDisplay($write_row_num, "Пустые")
;путь к файлу2
$sFile2 = @ScriptDir & "\Print.xls"
;открываем в скрытом режиме файл2
$fVisible = 1
;только для чтения файл2
$fReadOnly = True
;открыть книгу 2
Local $oExcel2 = _ExcelBookOpen($sFile2, $fVisible, $fReadOnly)
;номер цикла
$num_loop = 1
do
;выделяем копируем строку книги1
$oExcel.ActiveSheet.Range("A"&$write_row_num[$num_loop],"F"&$write_row_num[$num_loop]).Select
$oExcel.Selection.Copy
;выделяем вставляем строку в книгу2
$oExcel2.ActiveSheet.Range("A"&$num_loop+2,"F"&$num_loop+2). Select
$oExcel2.ActiveSheet.Paste
;переходим к следущей строке цикла
$num_loop = $num_loop +1
;делаем до того как строка цикла будет равна последней записи заполненых ячеек
until $num_loop = _ArrayMaxIndex($write_row_num, 1)
;ширина колонки заказа
$zakaz_dl = " ."
_ExcelWriteCell($oExcel2, $zakaz_dl, 1, 5)
;выставляем формат и ширину заказа
$oExcel2.Columns('A:F' ).EntireColumn.AutoFit
$oExcel2.Columns('A:F' ).EntireColumn.Select
$oExcel2.Selection.Interior.ColorIndex = 0
;удаляем ненужные колонки
_ExcelColumnDelete($oExcel2, 1, 1)
_ExcelColumnDelete($oExcel2, 2, 1)
_ExcelColumnDelete($oExcel2, 4, 1)
;вписываем заказ от
$zakaz_ot = _ExcelReadCell($oExcel, 14, 1)
_ExcelWriteCell($oExcel2, $zakaz_ot, 3, 1)
;вписываем поле заметок
$zametki = _ExcelReadCell($oExcel, 1, 7)
_ExcelWriteCell($oExcel2, $zametki, 2, 1)
;вписываем дату печати
$data = @MDAY&"."&@MON&"."&@YEAR&" в"&@HOUR&":"&@MIN
_ExcelWriteCell($oExcel2, $data, 2, 2)
;вписываем название файла
dim $name_file = StringSplit(StringReplace($sFile, "\", @LF), @LF)
$name_file_short = "файл: "&$name_file[$name_file[_ArrayMaxIndex($name_file, 1)]]
_ExcelWriteCell($oExcel2, $name_file_short, 1, 1)
;убираем жирный шрифт
_ExcelFontSetProperties($oExcel2, 1, 1, $num_loop+1, 3, False, False, False)
;~ MsgBox(4096, "Test", $name_file[$name_file[_ArrayMaxIndex($name_file, 1)]] )
;~ _ArrayDisplay($name_file, "Пустые")
Читайте также: