Компьютерный форум OSzone.net  

Компьютерный форум OSzone.net (http://forum.oszone.net/index.php)
-   Скриптовые языки администрирования Windows (http://forum.oszone.net/forumdisplay.php?f=102)
-   -   [решено] Открытие, изменение и сохранение книг Excel (http://forum.oszone.net/showthread.php?t=248610)

Vadikan 07-12-2012 13:04 2040594

[решено] Открытие, изменение и сохранение книг Excel
 
Всем привет!

Есть рутинная задача. Имеется папка с книгами Excel, в которых разное количество листов, но в каждом есть столбец B (с ячейкой B1=Owner). Нужен скрипт, который удалит все столбцы со всех листов во всех книгах.

Макросы по удалению такого столбца из одной книги вроде нагугливаются. Но хотелось бы решить поставленную задачу, чтобы не открывать каждую книгу.

Буду признателен за любую помощь.

Вадим

Iska 07-12-2012 16:31 2040723

Цитата:

Цитата Vadikan
удалит все столбцы со всех листов во всех книгах. »

«Все столбцы» — подходящие под условие столбцы B? Можно попробовать так:
читать дальше »
Код:

Option Explicit

Const xlWorksheet = &HFFFFEFB9


Dim strFolder

Dim objFSO
Dim objFile

Dim objExcel
Dim objWorksheet


If WScript.Arguments.Count = 1 Then
        strFolder = WScript.Arguments.Item(0)
       
        Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
       
        If objFSO.FolderExists(strFolder) Then
                Set objExcel = WScript.CreateObject("Excel.Application")
               
                For Each objFile In objFSO.GetFolder(strFolder).Files
                        Select Case LCase(objFSO.GetExtensionName(objFile.Name))
                                Case "xls", "xlsx"
                                        With objExcel.Workbooks.Open(objFile.Path)
                                                For Each objWorksheet In .Sheets
                                                        With objWorksheet
                                                                If .Type = xlWorksheet Then
                                                                        With .Cells.Item(1, 2)
                                                                                If .Value = "Owner" Then
                                                                                        .EntireColumn.Delete
                                                                                End If
                                                                        End With
                                                                End If
                                                        End With
                                                Next
                                               
                                                .Save
                                                .Close
                                        End With
                                Case Else
                                        ' Nothing to do
                        End Select
                Next
               
                objExcel.Quit
                Set objExcel = Nothing
        Else
                WScript.Echo "Folder [" & strFolder & "] not found"
        End If
Else
        WScript.Echo "Usage: cscript.exe //nologo " & WScript.ScriptName & " <Folder>"
End If

WScript.Quit 0


* писалось под 2003-им Microsoft Excel, потому крайне рекомендую сначала опробовать «на свинках»;
* не рекурсивно.

van1985 07-12-2012 17:12 2040758

Powershell

написал только что , так что без особого тестирования... Сначала лучше запустить на "кошках"
Excel 2007.

Код:

$xlCellTypeLastCell = 11
$xl = New-Object -com Excel.Application
$xl.Visible = $false
$xl.DisplayAlerts = $False

Get-ChildItem -Path c:\temp\excelRemouveColumn -Recurse -Include *.xlsx | %{
$wb = $xl.Workbooks.Open($_.fullname)

1..$wb.Worksheets.Count | %{
$ws = $wb.Worksheets.Item($_)
if($ws.cells.item(1,2).value() -eq "Owner"){
[void]$ws.columns.item(2).delete()
}
}
$wb.Save()
$wb.Close()
}
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
Remove-Variable xl

Upd. Язык Office 2013 должен совпадать с региональными стандартами

Vadikan 07-12-2012 18:59 2040822

Iska, спасибо за вариант, я ждал помощи от вас :)

К сожалению, получил ошибку
Код:

C:\Users\username\Documents\test\remove-column.vbs(31, 11) Microsoft VBScript runtime error: Type mismatch: 'Value'
У меня Office 2010.

van1985, кстати, я очень хотел посмотреть, не предложит ли кто-нибудь вариант с PowerShell. Я по гуглу такое не осилил, к сожалению. Большое спасибо, ненужные мне столбцы удалились везде. Нужные, вроде, не пропали :)

Vadikan 16-04-2013 22:07 2134051

Я временно сниму пометку решено и подниму тему.

Сейчас нужно решение именно на VBS под Office 2013 RT, потому что в Windows RT из пошика это не сделать. Для решения текущей задачи достаточно только поочередно открыть, сохранить и закрыть все книги XLS в заданной папке.

Вот тут есть очень похожее http://stackoverflow.com/questions/1...-automatically , надо на обработку папки переделать, но у меня с VBS совсем никак :)

Буду признателен любым идеям!

Iska 17-04-2013 04:49 2134178

Цитата:

Цитата Vadikan
потому что в Windows RT из пошика это не сделать. »

Там нет PowerShell'а?


Цитата:

Цитата Vadikan
Для решения текущей задачи достаточно только поочередно открыть, сохранить и закрыть все книги XLS в заданной папке. »

То бишь, со «внутренностями» документа никаких операций делать больше не надо?

Примерно так:
читать дальше »
Код:

Option Explicit

Dim objFSO
Dim objFile

Dim strFolder

Dim objSheet


Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

If WScript.Arguments.Count = 1 Then ' Если задан аргумент скрипта…
        ' …используем его как имя папки для обработки
        strFolder = WScript.Arguments.Item(0)
Else
        ' …иначе используем текущий каталог для скрипта
        strFolder = objFSO.GetAbsolutePathName(".")
End If

' В принципе, можно и прямо задать потребную папку для обработки
'strFolder = "c:\temp\excelRemouveColumn"

With WScript.CreateObject("Excel.Application")
        .DisplayAlerts = False
       
        If objFSO.FolderExists(strFolder) Then
                For Each objFile In objFSO.GetFolder(strFolder).Files
                        Select Case LCase(objFSO.GetExtensionName(objFile.Name))
                                Case "xls", "xlsx"
                                        With .Workbooks.Open(objFile.Path)
                                                'WScript.Echo objFile.Path
                                               
                                                .Save
                                                .Close
                                        End With
                                Case Else
                                        ' Nothing to do
                        End Select
                Next
        Else
                WScript.Echo "Folder [" & strFolder & "] not found."
        End If
       
        .Quit
End With

Set objFSO = Nothing

WScript.Quit


Vadikan 17-04-2013 11:16 2134328

Цитата:

Цитата Iska
Там нет PowerShell'а? »

Есть, но один специалист по нему сказал, что PS там урезан, поэтому код выше завершается с ошибками.

Цитата:

Цитата Iska
Примерно так: »

Спасибо, работает, но выводит диалог с именем каждого обработанного файла. Как его убрать?

Iska 17-04-2013 14:09 2134419

Цитата:

Цитата Vadikan
Есть, но один специалист по нему сказал, что PS там урезан, поэтому код выше завершается с ошибками. »

Спасибо, ясно.

Цитата:

Цитата Vadikan
выводит диалог с именем каждого обработанного файла. Как его убрать? »

Вариантов несколько. Проще всего закомментировать строку с «WScript.Echo …». Поправил код выше.

Vadikan 17-04-2013 21:45 2134720

Iska, да, так работает, но все равно не сработало в RT.

Цитата:

"Не удается создать объект с именем WScript.Shell".
Видимо, там и VBS какой-то не такой :)

Спасибо за помощь!

Iska 18-04-2013 00:18 2134808

Цитата:

Цитата Vadikan
Iska, да, так работает, но все равно не сработало в RT. »

Вот же зараза такая ;)!


Цитата:

Цитата Vadikan
Цитата:

"Не удается создать объект с именем WScript.Shell".
Видимо, там и VBS какой-то не такой »

Давайте попробуем дедовский способ получения текущего каталога — «objFSO.GetAbsolutePathName(".")» вместо использования объекта «WScript.Shell». Ещё раз поправил код.

Vadikan 18-04-2013 23:49 2135497

Iska, в общем, дело в том, что Office 2013 не поддерживает VBA/Activex :)

Iska 19-04-2013 05:07 2135554

Не понял, а как же: Справочник по языку Visual Basic для приложений для Office 2013?!

Лучше приведите ссылку/ссылки на указанный:
Цитата:

Цитата Vadikan
Office 2013 не поддерживает VBA/Activex »

концепт, может так пойму, про что речь.

Vadikan 19-04-2013 11:03 2135661

Iska, речь об Office 2013 RT, конечно. http://blogs.office.com/b/office-nex...indows-rt.aspx (differences)

Iska 20-04-2013 06:52 2136203

Vadikan, спасибо, ясно. Вот тут: Office Home & Student RT - Office.com подробнее об этом.

Vadikan 20-04-2013 12:06 2136295

Iska, там не подробнее, и именно по этой причине я дал другую ссылку.

Iska 20-04-2013 16:37 2136425

Vadikan, значит, я ничего не понимаю :(.

читать дальше »
Цитата:

Differences between Office for Windows and Office for Windows RT

Здесь скриншоты

Screen shots of the two applications look very similar because the products are very similar by design. Differences between the versions are subtle. Office Home & Student 2013 RT includes the vast majority of Office Home & Student 2013 features available on PCs, and the features customers use most. Windows RT tablets have special requirements for security, reliability, and battery life, and we’ve worked to ensure that the RT version is well-suited for the platform. Beyond the differences listed below, Office for Windows RT is fully-featured Office with complete document compatibility.
  • Macros, add-ins, and features that rely on ActiveX controls or 3rd party code such as the PowerPoint Slide Library ActiveX control and Flash Video Playback
  • Certain legacy features such as playing older media formats in PowerPoint (upgrade to modern formats and they will play) and editing equations written in Equation Editor 3.0, which was used in older versions of Office (viewing works fine)
  • Certain email sending features, since Windows RT does not support Outlook or other desktop mail applications (opening a mail app, such as the mail app that comes with Windows RT devices, and inserting your Office content works fine)
  • Creating a Data Model in Excel 2013 RT (PivotTables, QueryTables, Pivot Charts work fine)
  • Recording narrations in PowerPoint 2013 RT
  • Searching embedded audio/video files, recording audio/video notes, and importing from an attached scanner with OneNote 2013 RT (inserting audio/video notes or scanned images from another program works fine)


читать дальше »
Цитата:

What Office Home & Student 2013 features are unavailable in Office Home & Student 2013 RT?

Across multiple applications

1. Macros, Add-Ins, Forms, and Custom Programs (Word, Excel, PowerPoint)

In other versions of Office you or a software developer can use tools such as Visual Basic for Applications (VBA) to write and run macros and other custom programs in Office. VBA is not available for the applications in Office Home & Student 2013 RT.

To use macros, add-ins, forms with custom code, or other custom programs in Office documents, you need a version of Office other than Office Home & Student 2013 RT on a computer or tablet not powered by Windows RT. Other versions of Office cannot be installed on Windows RT devices. For example, Office Home & Student 2013 and Office Professional 2013 support these features but cannot be installed on Windows RT devices.

If you already use macros, add-ins, InfoPath forms with custom programs, or other custom programs in your PC or Mac version of Office, you will not be able to use them in Office Home & Student 2013 RT.

2. Send Email Features (Word, Excel, PowerPoint, OneNote)

Your Windows RT tablet does not support Outlook or other desktop email applications such as Mozilla Thunderbird or Opera. Due to this, certain email features available for Office documents in other Office versions are not supported in Office Home & Student 2013 RT:
  • "Send as … (attachment)" features in the Office Backstage view
  • Word mail merge features related to email
  • Sending email links to share slides using the PowerPoint Broadcast Slide Show button on the Slide Show tab
  • OneNote email share options and email-related options in the Tools/Options menu
  • Many email-related buttons in the Office Ribbon and Quick Assist Toolbar
Instead, you can open your Windows RT email app or use another email app that may be available from the Windows Store, manually create an email message and attach your document to it.

3. SkyDrive Sync Integration (Word, Excel, PowerPoint)

Office Home & Student 2013 RT does not support automatic synchronization between personal SkyDrive documents and your local disk. Instead, you can access SkyDrive through the Office Backstage view and use the Open or Save commands to open or save your documents.



Vadikan 21-04-2013 11:10 2136849

Iska, и? Я виже больше букв просто :) Зато о других вещах там не сказано практически.

Iska 21-04-2013 20:39 2137204

Vadikan, теперь ясно ;), разобрались. Я хотел прояснить для себя только вопрос касательно VBA.


Время: 11:25.

Время: 11:25.
© OSzone.net 2001-