Hi I wrote some code using VBScript on Excel sheet as below. Now everytime when the Script is done its processing it is prompting the user to Save
it.But I don’t want this,rather I want it to save it automatically without prompt.
CODE
Option Explicit
Dim objExcel1,strPathExcel1,objSheet1,objSheet5
Set objExcel1 = CreateObject("Excel.Application")'Object for Condition Dump
strPathExcel1 = "D:VAGE_Wing_To_Wing_Report.xlsx"
objExcel1.Workbooks.Open strPathExcel1
Set objSheet1 = objExcel1.ActiveWorkbook.Worksheets(1)
Set objSheet5 = objExcel1.ActiveWorkbook.Worksheets(5)
'=====================================================================================
'Here Bad sheet will be copied by the data from First sheet master data sheet
'=====================================================================================
ParentPIDFromMasterSheet objSheet1,objSheet5
'=====================================================================================
'Here Bad sheet will be copied by the data from First sheet master data sheet
'=====================================================================================
BadDataSelectionDel objSheet5
'=======================
objExcel1.ActiveWorkbook.SaveAs strPathExcel1
objExcel1.Workbooks.close
objExcel1.Application.Quit
'======================
STF
1,4653 gold badges19 silver badges36 bronze badges
asked Dec 26, 2012 at 7:08
Arup RakshitArup Rakshit
116k30 gold badges257 silver badges313 bronze badges
1
UNTESTED (Try this)
You need to set your workbook and then close it after saving it. Also it is a good practice to clean up your objects at the end of your code after use.
Option Explicit
Dim objExcel1, objWB, strPathExcel1, objSheet1, objSheet5
Set objExcel1 = CreateObject("Excel.Application") 'Object for Condition Dump
strPathExcel1 = "D:VAGE_Wing_To_Wing_Report.xlsx"
Set objWB = objExcel1.Workbooks.Open(strPathExcel1)
Set objSheet1 = objWB.Worksheets(1)
Set objSheet5 = objWB.Worksheets(5)
'=====================================================================================
'Here Bad sheet will be copied by the data from First sheet master data sheet
'=====================================================================================
ParentPIDFromMasterSheet objSheet1, objSheet5
'=====================================================================================
'Here Bad sheet will be copied by the data from First sheet master data sheet
'=====================================================================================
BadDataSelectionDel objSheet5
'=======================
objWB.Save
objWB.Close
objExcel1.Quit
'~~> Cleanup
Set objSheet1 = Nothing
Set objSheet5 = Nothing
Set objWB = Nothing
Set objExcel1 = Nothing
'======================
answered Dec 26, 2012 at 7:14
Siddharth RoutSiddharth Rout
146k17 gold badges206 silver badges250 bronze badges
3
You only need to add this line of code before saving your file :
objExcel1.Application.DisplayAlerts = False 'Prevents prompts from appearing
I tried it and it worked.
answered Mar 22, 2020 at 13:03
- Remove From My Forums
-
Question
-
I have the following VB script (I saved my VB script file as «open_document.vbs» and use Notepad as my editor):
Const xlDelimited = 1 Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.OpenText "C:Scriptsjun_24v.txt",,,xlDelimited,,,,,,,True,"~" ojbExcel.Save As "C:documents and settingsjeromezdesktopjun_24v.xls"
———————————————————-
PURPOSE OF SCRIPT:
once the txt file is open in Excel and parsed, I want the script to save the not as a txt, but as an Excel file using «Save as» file type «Excel» to my desktopbut it seems to save the file as «jun_24.xls» with the fileFormat as «Txt Delimited» and I want it to be «Microsoft Excel»
The file opens as an Excel file if I double-click on the file icon.
However, if I try to open the file from an instance of Excel (i.e. «File > Open») it still thinks the file is a text file and brings up the text box asking me if I want to «Delimted» or Fixed Width»
I would think after «Save As» I should be able to open file as an Excel file from Excel and not have to double-click on the icon
What am I doing wrong?
Any help would be appreciated
Thanks
-
Edited by
Tuesday, June 30, 2009 12:14 AM
-
Edited by
Answers
-
Sorry about the confusion, I have Excel 2007 and xlExcel8 was added for it, so the script errors out if you have Excel 2003. Try using xlWorkbookNormal (= -4143) instead. Here is th modified script:
Const xlDelimited = 1 Const xlWorkbookNormal = -4143 Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.OpenText "C:Scriptsjun_24v.txt", _ , , xlDelimited, , , , , , , True, "~" objExcel.Workbooks("jun_24v.txt").SaveAs _ "C:Scriptsjun_24v.xls", xlWorkbookNormal objExcel.Workbooks("jun_24v.xls").Close objExcel.Quit
urkec
-
Marked as answer by
jeromez
Tuesday, June 30, 2009 11:47 PM
-
Marked as answer by
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
‘ | |
‘ This VBS script opens an MS Excel Workbook, sets the active sheet, and saves that sheet to CSV. | |
‘ | |
‘ Usage: | |
‘ cscript //nologo saveascsv.vbs «source.xls» «worksheetname» «output.csv» | |
‘ cscript //nologo saveascsv.vbs «c:tempSaveAsCSVBook1.xlsx» «Sheet2» «c:tempSaveAsCSVoutput.csv» | |
‘ | |
if WScript.Arguments.Count < 3 Then | |
‘ One WScript.Echo in case user doesnt put cscript //nologo and would otherwise have to press enter a bunch of times. | |
WScript.Echo «Usage:» & vbCRLF & _ | |
» cscript //nologo « & Wscript.ScriptName & » «»source.xls»» «»worksheetname»» «»output.csv»»» & vbCRLF & _ | |
«» & vbCRLF & _ | |
» e.g.» & vbCRLF & _ | |
» cscript //nologo « & Wscript.ScriptName & » «»c:temptest.xls»» «»sheet2″» «»test-sheet2.csv»»» | |
‘ Quit with error. | |
Wscript.Quit 1 | |
End If | |
source = Wscript.Arguments.Item(0) | |
worksheetname = Wscript.Arguments.Item(1) | |
output = Wscript.Arguments.Item(2) | |
Dim oExcel | |
Set oExcel = CreateObject(«Excel.Application») | |
‘ Do not prompt to overwrite, just do it. | |
oExcel.DisplayAlerts = False | |
Dim oBook | |
Set oBook = oExcel.Workbooks.Open(source) | |
‘ Set the current worksheet | |
oBook.Worksheets(worksheetname).Activate | |
‘ Set the format to save as. Formats here: https://msdn.microsoft.com/en-us/library/office/ff198017.aspx | |
xlCSV = 6 | |
‘ Save the current sheet as CSV | |
oBook.SaveAs output, xlCSV | |
‘ Close the various objects. | |
oBook.Close False | |
oExcel.Quit | |
‘ Quit with no error | |
WScript.Quit 0 |
(Excel Object Model in VBScript)
Excel Application operations using Excel Application Object
Excel Application Object:
It is used to perform operations on Excel Application.
Create Excel Application Object:
Set Variable = CreateObject(“Excel.Application”)
———————-
Excel Application
Excel Workbook / File
Excel Worksheet / Sheet
Excel File Operations using VBScript Examples:
1) Create an Excel file
Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True ‘To view the operation (Creating Excel file) during Execution.
objExcel.Workbooks.Add ‘Create New Workbook / file
objExcel.ActiveWorkbook.SaveAs “C:UsersgcreddyDesktopQTP.xls” ‘Save the Excel workbook /file
objExcel.Quit ‘To close the Excel Application
Set objExcel = Nothing ‘To release the memory
—————————————————
2) Check the existence of QTP file, if not exist then create the file.Dim objFso, objExcel, FilePath
FilePath = “C:UsersgcreddyDesktopQTP.xls”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)
If Not objFso.FileExists(FilePath) Then
objExcel.Workbooks.Add ‘Create New Workbook / file
objExcel.ActiveWorkbook.SaveAs FilePath
objExcel.Quit
End If
Set objExcel = Nothing ‘To release the memory
—————————————————-
3) Check the existence of QTP file, if exists then open the file and enter some data, If not exist then create the file and enter some data (Using Excel Application Object only)
Dim objFso, objExcel, FilePath
FilePath = “C:UsersgcreddyDesktopQTP.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)
If Not objFso.FileExists(FilePath) Then
objExcel.Workbooks.Add
objExcel.Worksheets(1).Cells(1, 1) = “Hello UFT”
objExcel.ActiveWorkbook.SaveAs FilePath
Else
objExcel.Workbooks.Open (FilePath)
objExcel.Worksheets(1).Cells(1, 1) = “Hello UFT”
objExcel.ActiveWorkbook.Save
End If
objExcel.Quit
Set objExcel = Nothing
Excel Objects
1) Excel Application Object
It is used to perform operations on Excel Application.
Set Variable = CreateObject(“Excel.Application”)
——————————–
2) Excel Workbook object
It is used to work with specified Excel file / Workbook
Set Variable = ExcelApplicationObject.Workbooks.Add / Open(“Filepath”)
——————————–
3) Excel Worksheet object
It is used to work with specified work sheet
Set Varaible = ExcelWorkbookObject.Worksheets(Sheet Id / “Sheet name”)
——————————————————-
Excel Application is always only one.
We may have one or more Workbooks.
We may have multiple sheets in every workbook.
———————————————
> Using (“Excel.Application”) class value we create Excel Application Object.
> We create Excel Workbook object using Excel Application Object.
> We create Excel Worksheet object using Excel workbook object.
————————————–
Difference between File system object model and Excel object model in case of Sub objects.
In File system object model creating Text stream object is mandatory to perform File internal operations like Read, Write, Compare, Search etc…
In Excel Object model creating sub and sub-sub objects optional, if you want to work with multiple files and multiple sheets then we can use sub and sub-sub objects.
———————————————————-
4) Check the existence of QTP file, if exists then open the file and enter some data, If not exist then create the file and enter some data (Using Main and sub objects)
Dim objFso, objExcel, objWorkbook, objWorksheet, FilePath
FilePath = “C:UsersgcreddyDesktopQTP.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)
If Not objFso.FileExists(FilePath) Then
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1, 1) = “Hello UFT”
objWorkbook.SaveAs FilePath
Else
Set objWorkbook = objExcel.Workbooks.Open (FilePath)
Set objWorksheet = objworkbook.Worksheets(1)
objWorksheet.Cells(1, 1) = “Hello UFT”
objWorkbook.Save
End If
objExcel.Quit
Set objExcel = Nothing
————————————————
5) Read data form Excel file and perform Data driven Testing for Login Functionality.
Dim objExcel, objWorkbook, objWorksheet, i, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersgcreddyDesktopQTP.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)
RowsCount = objWorksheet.UsedRange.Rows.Count
For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i is Row, A is Column Name
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2) ‘ 2 is Column id
wait 2
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).Close
Next
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
————————————————
6) Read data form Excel file and perform Data driven Testing for Login Functionality. And write Test Result to the Same file 3rd column.
Dim objExcel, objWorkbook, objWorksheet, i, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersgcreddyDesktopQTP.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)
RowsCount = objWorksheet.UsedRange.Rows.Count
For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i is Row, A is Column Name
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2) ‘ 2 is Column id
wait 2
Dialog(“Login”).WinButton(“OK”).Click
If Window(“Flight Reservation”).Exist (12) Then
Window(“Flight Reservation”).Close
objWorksheet.Cells(i, 3) = “Login Successful – Passed”
Else
SystemUtil.CloseDescendentProcesses
objWorksheet.Cells(i, 3) = “Login Unsuccessful – Failed”
End If
Next
objWorkbook.Save
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
————————————————
7) Read data form Excel file and perform Data driven Testing for Login Functionality. And write Test Result and Error messages to the same file.Dim objExcel, objWorkbook, objWorksheet, i, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersgcreddyDesktopQTP.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)
RowsCount = objWorksheet.UsedRange.Rows.Count
For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i is Row, A is Column Name
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2) ‘ 2 is Column id
wait 2
Dialog(“Login”).WinButton(“OK”).Click
If Window(“Flight Reservation”).Exist (12) Then
Window(“Flight Reservation”).Close
objWorksheet.Cells(i, 3) = “Login Successful – Passed”
Else
objWorksheet.Cells(i, 4) = Dialog(“Login”).Dialog(“Flight Reservations”).Static(“Agent name must be at”).GetROProperty(“text”)
SystemUtil.CloseDescendentProcesses
objWorksheet.Cells(i, 3) = “Login Unsuccessful – Failed”
End If
Next
objWorkbook.Save
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
——————————————–
Read Button Names from Login Dialog and export to Excel file 2nd sheet.Dim objExcel, objWorkbook, objWorksheet, oButton, Buttons, i
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook= objExcel.Workbooks.Open (“C:UsersgcreddyDesktopQTP.xlsx”)
Set objworksheet = objWorkbook.Worksheets(2)
Set oButton = Description.Create
oButton(“Class Name”).Value = “WinButton”
Set Buttons = Dialog(“Login”).ChildObjects(oButton)
Msgbox Buttons.Count
objWorksheet.cells(1, 1) = “Button Names”
For i = 0 To Buttons.Count – 1 Step 1
objWorksheet.cells(i+2, 1) = Buttons(i).GetRoProperty(“text”)
Next
objWorkbook.Save
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objexcel = Nothing
—————————————————
9) Read Link names from Google Home page and export to Excel file 3rd sheet.Dim objExcel, objWorkbook, objWorksheet, oLink, Links, i
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook= objExcel.Workbooks.Open (“C:UsersgcreddyDesktopQTP.xlsx”)
Set objworksheet = objWorkbook.Worksheets(3)
Set oLink = Description.Create
oLink(“micclass”).Value = “Link”
Set Links = Browser(“Google”).Page(“Google”).ChildObjects(oLink)
Msgbox Links.Count
objWorksheet.cells(1, 1) = “Link Names”
For i = 0 To Links.Count – 1 Step 1
objWorksheet.cells(i+2, 1) = Links(i).GetRoProperty(“text”)
Next
objWorkbook.Save
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objexcel = Nothing
—————————————————
10) Read Customer names from 1 to 10 Records and export to Excel
Dim objExcel, objWorkbook, objWorksheet, Customer_Name, i
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook= objExcel.Workbooks.Open (“C:UsersgcreddyDesktopQTP.xlsx”)
Set objworksheet = objWorkbook.Worksheets(2)
objWorksheet.cells(1, 1) = “Customer Names”
For i = 1 To 10 Step 1
Window(“Flight Reservation”).Activate
Window(“Flight Reservation”).WinButton(“Button”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinCheckBox(“Order No.”).Set “ON”
Window(“Flight Reservation”).Dialog(“Open Order”).WinEdit(“Edit”).Set i
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
Customer_Name = Window(“Flight Reservation”).WinEdit(“Name:”).GetROProperty(“text”)
objWorksheet.Cells(i+1, 1) = Customer_Name
Next
objWorkbook.Save
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objexcel = Nothing
————————————————–
11) Create an Excel File and Rename 1st sheet as “Module”, 2nd sheet as “TestCase”, and 3rd sheet as “TestStep”.
Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Workbooks.Add
objExcel.Worksheets(1).Name = “Module”
objExcel.Worksheets(2).Name = “TestCase”
objExcel.Worksheets(3).Name = “TestStep”
objExcel.ActiveWorkbook.SaveAs “C:UsersgcreddyDesktopQTP2.xlsx”
objExcel.Quit
Set objExcel = Nothing
12) Create an Excel file and Add one more sheet.Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Workbooks.Add ‘Create New workbook
objexcel.Worksheets.Add ‘Create New worksheet
objExcel.ActiveWorkbook.SaveAs “C:UsersgcreddyDesktopQTP3.xlsx”
objExcel.Quit
Set objExcel = Nothing
———————————————
Assignment:
Create an Excel file and Move 1st sheet to 3rd position.
Creation Time:
Sheet1 Sheet2 sheet3
Move 1st sheet to 3rd position
Sheet2 Sheet3 Sheet1
————————————————–
Comparison examples:
i) One to one comparison (Textual and binary)
ii) Many to many comparison
————————————————-
Follow me on social media:
8 / 8 / 1 Регистрация: 09.10.2013 Сообщений: 613 |
|
1 |
|
VBS Сохранение открытого экселевского файла12.02.2015, 09:32. Показов 2892. Ответов 10
Как сохранить открытый экселевский файл с текущей датой в имени файла.Сохранение осуществить в ту же папку, где и был открыт экселевский файл. Буду рад любой помощи. Заранее благодарен!
0 |
Pure Free Digital Ghost 4603 / 1915 / 372 Регистрация: 06.01.2013 Сообщений: 4,569 |
|
12.02.2015, 10:25 |
2 |
adb420, Вам это необходимо именно скриптом на VBS или все же макросом на VBA?
0 |
8 / 8 / 1 Регистрация: 09.10.2013 Сообщений: 613 |
|
12.02.2015, 10:42 [ТС] |
3 |
FraidZZ, хотелось бы все таки скриптом на vbs, но если vbs никак, то можно и макрасом на vba будет
0 |
Surrogate Ушел с CyberForum совсем! 873 / 182 / 25 Регистрация: 04.05.2011 Сообщений: 1,020 Записей в блоге: 110 |
||||
12.02.2015, 11:29 |
4 |
|||
в vba работает. а в vbs в 25 строке ошибку находит
0 |
8 / 8 / 1 Регистрация: 09.10.2013 Сообщений: 613 |
|
12.02.2015, 11:34 [ТС] |
5 |
Surrogate,
а в vbs в 25 строке ошибку находит так код из 16 строк состоит, который Вы мне скинули
0 |
Surrogate Ушел с CyberForum совсем! 873 / 182 / 25 Регистрация: 04.05.2011 Сообщений: 1,020 Записей в блоге: 110 |
||||
12.02.2015, 11:48 |
6 |
|||
попробуй этот, что не идет в vbs
0 |
adb420 8 / 8 / 1 Регистрация: 09.10.2013 Сообщений: 613 |
||||
12.02.2015, 12:01 [ТС] |
7 |
|||
Surrogate, что то все равно не так работает. из под vba, не понятно куда сохраняет(не сохраняет в ту папку, где был открыт файл эксель), из под vbs ругается на 26 строку
убрал :, оставил просто =, ругаться перестал, но и не сохраняет тоже
0 |
Surrogate Ушел с CyberForum совсем! 873 / 182 / 25 Регистрация: 04.05.2011 Сообщений: 1,020 Записей в блоге: 110 |
||||
12.02.2015, 13:16 |
8 |
|||
Сообщение было отмечено adb420 как решение Решениедумаю это излишне закрывать открытую книгу экселя. это мой второй опыт работы с VBS
вроде работает
1 |
8 / 8 / 1 Регистрация: 09.10.2013 Сообщений: 613 |
|
12.02.2015, 13:43 [ТС] |
9 |
Surrogate, и в правду работает!) спасибо) Добавлено через 6 минут
0 |
Surrogate Ушел с CyberForum совсем! 873 / 182 / 25 Регистрация: 04.05.2011 Сообщений: 1,020 Записей в блоге: 110 |
||||
12.02.2015, 17:12 |
10 |
|||
надеюсь на помощь и в этих двух вопросах!) Не по теме: надеюсь кто-нибудь еще откликнется, сегодня я уже не помошник Добавлено через 3 часа 13 минут
Добавлено через 11 минут
0 |
17992 / 7618 / 890 Регистрация: 25.12.2011 Сообщений: 11,351 Записей в блоге: 17 |
|
24.02.2015, 19:22 |
11 |
Surrogate,
1 |
В данной статье я научу вас автоматизировать Microsoft Excel средствами VBS.
В прошлой статье я описывал работу с Word.
Привожу сразу код, так как он подробно прокомментирован:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Option Explicit Dim oExcelApp ‘ Объявляем переменные Dim oRangeD2D8 Dim oRangeH2J8 Set oExcelApp = CreateObject(«Excel.Application») ‘ Создаём объект с Excel—ем oExcelApp.Visible = True ‘ Делаем Excel видимым oExcelApp.Workbooks.Add ‘ Добавляем книгу в Excel oExcelApp.Cells(2,2).Font.Bold = True ‘ Делаем текст жирным в ячейке 1,1 oExcelApp.Cells(2,2).Font.Size = 20 ‘ Устанавливаем размер шрифта oExcelApp.Cells(2,2).Font.ColorIndex = 2 ‘ Устанавливаем цвет текста oExcelApp.Cells(2,2).Interior.ColorIndex = 1 ‘ Устанавливаем цвет ячейки oExcelApp.Cells(2,2).Value = «Test» ‘ Добавляем данные Set oRangeD2D8 = oExcelApp.Range(«D2″,»D8») ‘ Получаем доступ к ряду ячеек oRangeD2D8.Font.Size = 16 ‘ Устанавливаем размер шрифта oRangeD2D8.Font.Italic = True ‘ Делаем курсивный текст oRangeD2D8.Font.Underline = True ‘ Делаем текст подчёркнутым oRangeD2D8.Value = «Test» ‘ Устанавливаем для всех них текст Dim i For i = 2 To 6 oExcelApp.Cells(i,6).Value = i ‘ заполняем ячейки числами Next oExcelApp.Cells(8,6).Font.Bold = True oExcelApp.Cells(8,6).Font.Underline = True oExcelApp.Cells(8,6).Font.Size = 24 oExcelApp.Cells(8,6).Formula = «=SUM(F2:F6)» ‘ Добавляем формулу, которая в ячейке F8 отобразит сумму ранее добавленных цифр Set oRangeH2J8 = oExcelApp.Range(«H2»,«J8») ‘ Получаем доступ к ячейкам H2:J8 oRangeH2J8.Merge ‘ Объединяем группу ячеек oExcelApp.Save ‘ Сохраняем Excel файл oExcelApp.Quit ‘ Закрываем Excel |
Результат работы скрипта:
Помогла ли вам данная статья, ответьте в комментариях.
Загрузка…
Формулировка задачи:
Подкинули скрипт vbs, он открывает выбранный xls файл (выгруженный в формате Excel5 из сторонней программы) и перетасовывает данные.
Нужно добавить в скрипт сохранение под новым именем и в формате Excel2003.
Запарился с синтаксисом SaveAs
set xls=CreateObject(«Excel.Application»)
path=xls.GetOpenFileName()
set wrkbook=xls.Workbook.Open(path)
‘Добавляю
namenew=wrkbook.path & «new_» & wrkbook.name
дальше по отдельности
wrkbook.SaveAs (namenew) файл сохраняет под новым именем
wrkbook.SaveAs FileFormat=xlExcel11 Создает новый файл с именем True.xls и формат у него не меняется на Excel2003 (остается формат исходного Excel5)
Совместно использовать эти параметры не получается, никакой из синтаксисов найденных на форуме и в сети не подходит
Пробую
wrkbook.SaveAs Filename:=namenew, FileFormat:=xlExcel11
Выдает ошибку на двоеточие.
Убираю убираю двоеточие, создается файл правильного формата но с именем False.xls
Если взять в скобки wrkbook.SaveAs (Filename=namenew, FileFormat=xlExcel11 ) или так
wrkbook.SaveAs (namenew, xlExcel11) то возникает сообщение об ошибке «Недопустимо использование скобок при вызове процедуры Sub»
Кто сталкивался помогите пожалуйста.
Код к задаче: «Синтаксис SaveAs в vbs скрипте»
textual
<font color="blue">Set</font> xls = CreateObject(<font color="teal">"Excel.Application"</font>) <font color="blue">Set</font> wrbook = xls.Workbooks.<font color="blue">Open</font>(<font color="teal">"c:b5.xls"</font>) wrbook.SaveAs <font color="teal">"c:b2003.xls"</font>, -<font color="darkblue"><b>4143</b></font> <font color="blue">Set</font> wrbook = <font color="blue">Nothing</font> xls.Visible = True <font color="blue">set</font> xls = <font color="blue">Nothing</font>
Полезно ли:
7 голосов , оценка 3.857 из 5