Set objexcel excel application

Задача по объединению данных из нескольких Excel-файлов, или подгрузка доп.данных из внешнего файла решается достаточно просто: создается объект Excel, который можно скрыть визуально, затем открывается необходимый файл и выполняются нужные действия. Просто приведу несколько примеров.

Открытие файла Excel

Set objExcel = New Excel.Application
objExcel.Visible = False
Set wb = objExcel.Workbooks.Open(fname)
Set ws = wb.Sheets(1)

В первой строке запускаем новый Excel, затем делаем его невидимым, в 3-й строке открываем файл fname. В последней строке получаем первый лист открытого excel-кого файла.

Альтернативный вариант открытия файла

Set objExcel = New Excel.Application
Set wb = objExcel.Workbooks
wb.Open fname, local:=True
Set ws = wb.Item(1).ActiveSheet

При открытии файла можно использовать доп.параметры (приведу некоторые):

UpdateLinks — обновлять или нет внешние ссылки при открытии файла;
ReadOnly — открытие в режиме только для чтения;
Format — используемый при открытии разделитель (1 — символ tab, 2 — запятые, 3 — пробелы, 4 — точка с запятой, 5 — без разделителя, 6 — пользовательский разделитель, заданный в Delimiter);
Delimiter — пользовательский разделитель (в случае, если Format = 6);
Origin — тип операционной системы (xlMacintosh, xlWindows или xlMSDOS);
Local — использование в Excel языка такого же, как в открываемом файле.

Теперь можно выполнять какие-то действия с открытым файлом, просто обращаясь через wb и ws.

ws.Cells(1, 1).Value = "Test"
ws.Cells(1, 1).Font.Size = 18 ' Поменять размер шрифта
ws.Cells(1, 1).HorizontalAlignment = xlCenter ' 

Записать книгу и закрыть

wb.Save ' Записать с тем же именем
wb.SaveAs Filename:="имя_нового_файла", FileFormat:=xlOpenXMLWorkbookMacroEnabled ' Записать в новый файл
wb.Close ' Закрыть книгу

Для записи текущей книги (где находится макрос), можно использовать:

ActiveWorkbook.SaveAs 

Чтобы сохранить или перезаписать книгу Excel без вопросов, можно применить такой вариант:

Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="c:Temp001.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = True

У метода SaveAs есть несколько параметров сохранения, с ними можно ознакомиться на сайте Microsoft.

Если нужно, можно закрыть книгу Excel без сохранения изменений таким образом:

wb.Close False

It is used to Perform Operations on Excel Application.

Excel Application

Excel File / Excel Workbook

Excel Sheet / Excel Worksheet

Create Excel Application Object

Syntax:

Set variable = CreateObject(“Class value”)

example

Set objExcel = CreateObject(“Excel.Application”)

VBScript Excel Scripting Examples:

1) Create an Excel file

Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True ‘To view the Operation during execution
objExcel.Workbooks.Add ‘To create new file
objExcel.ActiveWorkbook.SaveAs “C:UsersG C REDDYDesktopJanuary.xlsx”
objExcel.Quit ‘To close the Excel Application
Set objExcel = Nothing

2) Check the existence of January file, If not exists then create the file.

Dim objFso, objExcel
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(“C:UsersG C REDDYDesktopJanuary.xlsx”) Then
objExcel.Workbooks.Add ‘To create new file
objExcel.ActiveWorkbook.SaveAs “C:UsersG C REDDYDesktopJanuary.xlsx”
End If
objExcel.Quit
Set objExcel = Nothing

3) Check the existence of January file, If exists then open the file and enter some data. if not exists then create the file and enter some data.

Dim objFso, objExcel, FilePath
FilePath = “C:UsersG C REDDYDesktopJanuary.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If objFso.FileExists(FilePath) Then
objExcel.Workbooks.Open(FilePath)
objExcel.Worksheets(1).Cells(1,1) = “Hello UFT”
objExcel.ActiveWorkbook.Save
Else
objExcel.Workbooks.Add
objExcel.Worksheets(1).Cells(1,1) = “Hello UFT”
objExcel.ActiveWorkbook.SaveAs(FilePath)
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 Excel files/Workbooks

Set variable = ExcelApplicationObject.Workbooks.Add/Open(“File Path”)

3) Excel Worksheet Object
It is used to work with Excel Sheets/Worksheets

Set variable = ExcelWorkbookObject.Worksheets(Sheet Id Or “Sheet Name”)

Excel Application Object is always only one

We can create one or more Excel Workbook objects

We can create one or more Excel Worksheet objects for every workbook object

Difference between FileSystemObject model and Excel object model in case of Sub Objects.

> In FileSystemObject model creating Text stream object (sub object) is mandatory to perform Text(Read, write etc…) related operations

> In Excel object model creating sub objects is optional, but if you want work with multiple files and multiple sheets then sub objects are required.

4) Check the existence of January file, If exists then open the file and enter some data. if not exists then create the file and enter some data.(Using Sub and Sub-sub objects)

Dim objFso, objExcel, FilePath, objWorkbook, objWorksheet
FilePath = “C:UsersG C REDDYDesktopJanuary.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If objFso.FileExists(FilePath) Then
Set objWorkbook = objExcel.Workbooks.Open(FilePath)
Set objworksheet = objWorkbook.Worksheets(1)
objWorksheet.cells(1, 1) =”Hello UFT”
objWorkbook.Save
Else
Set objWorkbook = objExcel.Workbooks.Add
Set objworksheet = objWorkbook.Worksheets(1)
objWorksheet.cells(1, 1) =”Hello UFT”
objWorkbook.SaveAs(FilePath)
End If
objExcel.Quit
Set objWorksheet = Nothing
Set objworkbook = Nothing
Set objExcel = Nothing

5) Read Test data from an Excel file and perform Data driven testing for Login Functionality

Dim objExcel, objWorkbook, objWorksheet, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersG C REDDYDesktopJanuary.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 for Row, A for Column
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2)’i for Row, 2 for Column
Wait 2
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).Close
Next
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing

Follow me on social media:

Hi,

I am trying to open a password protected Excel 2010 file from within Access 2010. The file contains a list of passwords which I do not want the user to see in Access — so instead Access should open the file behind the scenes and extract the relevant password
data, without the user seeing what’s happening in the background.

I tried using ADODB.Connection to do this but realised that it will not work with a password protected file. I also tried importing the Excel sheet into a table using VBA but yet again the password creates a problem.

Instead, I’m now using CreateObject(«Excel.Application») which works but with 1 problem: Excel loads but comes up with a message saying it cannot find an XLA file which it is looking for (unsure why — seems to be related to the ribbon). The problem
is I don’t want the user to see or interact with Excel so any errors should just be bypassed by Excel and not displayed on the screen. I saw the idea of using
Application.Visible = False and Application.DisplayAlerts = False, but these can only be set after the object is created so they do not help.

Is there any way of supressing these error messages at the point when the Excel.Application object is created? Alternatively if anyone can suggest a better way of accessing a password protected Excel file, feel free!

Another alternative I tried was to use CreateObject(«Excel.Sheet«) instead. This got rid of the XLA error as it loads all add-ins. However, all the addin splash screens appear and while all the add-ins are loading, I get error
«Automation error. The message filter indicated that the application is busy«. I can’t seem to win!

Many thanks for your help!

  • Remove From My Forums
  • Question

  • Hello all,

    First, I created a workbook (Horray!! I can copy an paste code.  Yeah, big deal).  Then I changed the name of the first worksheet to 2011.  Ok, worked great (I am almost coding on my own!  Or so I thought.)  Now, I am trying to name
    a bunch of worksheets in a sequence of years starting with the current year first.  The array will count backwards to the year 2003.  When I first got the «subscript out of range» error, I thought it was because I was using a counter that
    was bigger than the total amount of worksheets in the workbook.  When I adjusted the «For i = 1 To 9» to «For i = 1 To 3» it did not matter.  Now I think it has something to do with the argument in «Set objWorksheet = objWorkbook.Worksheets(i)». 
    With the emphasis on (i) part.  That is because when I just named the first worksheet, it read like this:  «Set objWorksheet = objWorkbook.Worksheets(1)».  I figured out that the «(1)» meant the first worksheet.  If it had been a «(2)»
    it would name the second worksheet.  Actually, I did not try that…. be right back….  Ok, yes that is precisely what happens.  I just went back and named the 2nd worksheet «2010».  So, I am not sure what the subscript out of range is
    about.  I always got to come here because I can never find the documentation on specific stuff like this.  Not that it is a bad thing, because you guys have been great.

    Here is my code:

    Dim strFileName

    strFileName = «I:Shared DocumentsadminMy DocumentsVBADailyNumberMidDayDailyMidDay.xls»

    Set objFSO = CreateObject(«Scripting.FileSystemObject»)
    Set objExcel = CreateObject(«Excel.Application»)

      objExcel.Visible = True
      objExcel.DisplayAlerts = False

     If objFSO.FileExists(strFileName) Then

      
      Set objWorkbook = objExcel.Workbooks.Open(strFileName)
      Set objWorksheet = objWorkbook.Worksheets(i)
      x = 2011

      
      For i = 1 To 3
      objWorksheet.Name = x
      x=x-1
      Next
      objWorkbook.SaveAs(strFileName)
      objExcel.Quit
     Else

      Set objWorkbook = objExcel.Workbooks.Add()
      Set objWorksheet = objWorkbook.Worksheets(i)
      x = 2011

      
      For i = 1 To 3
      objWorksheet.Name = x
      x=x-1
      Next
      objWorkbook.SaveAs(strFileName)
      objExcel.Quit
     End If

    I am working straight out of notepad on this… hang on.  I have vbsedit…. let me see something.  Yeah, it says: 

    System:  The storage control block address is invalid.

    So I am guessing I can’t put (i) in place of an actual worksheet number.  Will somebody help me out with this please?

    Thanks a bunch!


    Student

Answers

  • This will build you workbook with 10 sheets numbered 2011 — 2020

    [code]

    strFileName = «I:Shared DocumentsadminMy DocumentsVBADailyNumberMidDayDailyMidDay.xls»

    Set objFSO = CreateObject(«Scripting.FileSystemObject»)
    Set objExcel = CreateObject(«Excel.Application»)
    objExcel.Visible = True
    objExcel.DisplayAlerts = False

    If Not objFSO.FileExists(strFileName) Then
     
         Set objWorkbook = objExcel.Workbooks.Add()
        
         For i = 1 To 10
           j=objWorkbook.Worksheets.Count
           Set objWorksheet = objWorkbook.Worksheets.Add(Null,objWorkbook.Worksheets(j))
           x = 2010 + i
           objWorksheet.Name = x
         Next
        
         For Each sht In objWorkbook.Worksheets
              WScript.Echo sht.Name
              If InStr(sht.Name,»Sheet») Then
                   sht.Delete
              End if
         Next
        
         objWorkbook.SaveAs(strFileName)
         objExcel.Quit
     
    End If
     
    objWorkbook.SaveAs(strFileName)
    objExcel.Quit

    [/code]


    jv

    • Marked as answer by

      Wednesday, October 5, 2011 2:29 AM

January 31st, 2005

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I open an existing Excel spreadsheet, add some additional information to that spreadsheet, and then save my changes? Every time I call the SaveAs method a dialog box pops up asking me if I want to save my changes.

— RW

SpacerHey, Scripting Guy! AnswerScript Center

Hey, RW. Generally speaking, you can avoid that dialog box by using the Save method rather than the SaveAs method. If you open an existing spreadsheet and make some changes to it, just call the Save method; that should save your document without displaying the confirmation dialog box. For example, here’s a sample script that opens the file C:ScriptsTest.xls, writes the current date and time into cell A1, saves the file, and then quits:

Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open(“C:ScriptsTest.xls”)
Set objWorksheet = objWorkbook.Worksheets(1)

objWorksheet.Cells(1, 1).Value = Now objWorkbook.Save() objExcel.Quit

In most cases, that should do the trick. However, it’s also true that the SaveAs method offers more options than the Save method. If you want to add password protection to the spreadsheet, create a backup version of the file, or save in another format, you’ll need to use SaveAs. Likewise, suppose that every morning you run a script that grabs some data and populates cells in a brand-new spreadsheet. Every morning you want to save that file as C:ScriptsDaily_report.xls. Because this is a new spreadsheet (remember, you didn’t open the existing Daily_report.xls), you need to use the SaveAs method. And, when you do, a dialog box will pop up telling you that a file by that name already exists and asking you if you want to replace it.

So how do you get around these dialog boxes? The secret is to set the DisplayAlerts property (part of the Excel Application object) to FALSE. The DisplayAlerts property suppresses the display of dialog boxes and alert messages; instead of allowing you to choose whether to do X, Y, or Z, Excel automatically selects the default action for you. The default action for overwriting existing files is Yes. So when DisplayAlerts is set to False, the revised worksheet will be saved and you won’t be nagged and bothered by dialog boxes. Here’s a sample script that sets DisplayAlerts to FALSE and then uses the SaveAs method to save the changes:

Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
objExcel.DisplayAlerts = FALSE

Set objWorkbook = objExcel.Workbooks.Open(“C:ScriptsTest.xls”) Set objWorksheet = objWorkbook.Worksheets(1)

objWorksheet.Cells(1, 1).Value = Now objWorkbook.SaveAs(“C:ScriptsTest.xls”) objExcel.Quit

And just for the heck of it, here’s a script that creates a new worksheet and then overwrites an existing worksheet, again by setting DisplayAlerts to FALSE and by using SaveAs:

Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
objExcel.DisplayAlerts = FALSE

Set objWorkbook = objExcel.Workbooks.Add Set objWorksheet = objWorkbook.Worksheets(1)

objWorksheet.Cells(1, 1).Value = Now objWorkbook.SaveAs(“C:ScriptsTest.xls”) objExcel.Quit

If you’re having problems saving files, setting DisplayAlerts to FALSE will more than likely take care of things for you.

Понравилась статья? Поделить с друзьями:
  • Set nothing excel vba
  • Set macro in excel
  • Service times at the word church
  • Set hyperlink in word
  • Service is just a word