Vbs как открыть excel файл

Доброго всем дня. Очень надеюсь, что среди знатоков есть специалисты по данному языку.
Проблема у меня следующая. Требуется в vbs-скрипте прописать процедуру открытия книги и запуска макрос. С этим справиться удалось.

Код
Option Explicit
Dim app, ChangePhonesFolder, ChangePhonesFileName, inChangePhonesFullFileName, InFolderName, objExcel
Dim f, s, b, i, my_time, logs

set objExcel = CreateObject ("Excel.Application")
app="С:EXTUnZip.xlsb"

on error goto 0: TI_Avaya()

sub TI_Avaya()
   objExcel.Visible = true
        objExcel.Workbooks.Open (app)
   objExcel.run "Time_Indicators"
   objExcel.Workbooks("UnZip.xlsb").Close (true)
objExcel.Quit
end sub

Но вот как открыть документ, в режиме редактирования, если стоит соответствующий пароль. Метод vbа

Код
objExcel.Workbooks.Open (app, writerespassword:="123")

тут не подошел.

Use VBScript to create, open, and edit excel files. ( Excel needs to be installed on your computer ).


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

Show hidden characters

‘Microsoft Excel Automation Basics
‘:: Create and edit an Excel File.
‘———————————
‘create the excel object
Set objExcel = CreateObject(«Excel.Application»)
‘view the excel program and file, set to false to hide the whole process
objExcel.Visible = True
‘add a new workbook
Set objWorkbook = objExcel.Workbooks.Add
‘set a cell value at row 3 column 5
objExcel.Cells(3,5).Value = «new value»
‘change a cell value
objExcel.Cells(3,5).Value = «something different»
‘delete a cell value
objExcel.Cells(3,5).Value = «»
‘get a cell value and set it to a variable
r3c5 = objExcel.Cells(3,5).Value
‘save the new excel file (make sure to change the location) ‘xls for 2003 or earlier
objWorkbook.SaveAs «C:UsersUserNameDesktopvbsTest.xlsx»
‘close the workbook
objWorkbook.Close
‘exit the excel program
objExcel.Quit
‘release objects
Set objExcel = Nothing
Set objWorkbook = Nothing


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

Show hidden characters

‘Microsoft Excel Automation Basics
‘:: Open and edit an Excel File.
‘———————————
‘create the excel object
Set objExcel = CreateObject(«Excel.Application»)
‘view the excel program and file, set to false to hide the whole process
objExcel.Visible = True
‘open an excel file (make sure to change the location) .xls for 2003 or earlier
Set objWorkbook = objExcel.Workbooks.Open(«C:UsersUserNameDesktopvbsTest.xlsx»)
‘set a cell value at row 3 column 5
objExcel.Cells(3,5).Value = «new value»
‘change a cell value
objExcel.Cells(3,5).Value = «something different»
‘delete a cell value
objExcel.Cells(3,5).Value = «»
‘get a cell value and set it to a variable
r3c5 = objExcel.Cells(3,5).Value
‘save the existing excel file. use SaveAs to save it as something else
objWorkbook.Save
‘close the workbook
objWorkbook.Close
‘exit the excel program
objExcel.Quit
‘release objects
Set objExcel = Nothing
Set objWorkbook = Nothing

Not very sure to fully understand your question, but I already see one or 2 fixes:

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("c:UsersdrDesktoptest.xlsx")

objExcel.Application.Visible = True
'objExcel.Workbooks.Add
objWorkbook.Sheets("sheetName").Cells(3, 2).Value = "=today()"

WScript.Sleep 120000

objWorkbook.SaveAs "F" & format(date(), "yyyymmdd") & ".xlsm", 52

Anyway, changing the formula in B3 to "=Today()" everyday is totally useless, since it was already that same formula the day before.


Edit: if you are running this from an Excel VBA procedure, you don’t need to create a new instance of Excel:

dim sFolder as string
sFolder = "c:UsersdrDesktop"
Set objWorkbook = Workbooks.Open(sFolder & "test.xlsx")
objWorkbook.Sheets("sheetName").recalc
objWorkbook.SaveAs sFolder & format(date(), "yyyymmdd") & ".xlsx"
objWorkbook.Close

Открыть файл Ексель скриптом формата vbs

Egider

Дата: Вторник, 14.01.2020, 19:24 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Использую для запуска файла Запуск.xlsm созданный скрипт Запуск.vbs, с записанным в его модуль книги текстом:
[vba]

Код

Запуск
Sub Запуск()
    Dim objXL
    Dim Secur
    Set objXL = CreateObject(«Excel.Application»)
    objXL.Visible = TRUE
    secur = objXL.AutomationSecurity
    objXL.AutomationSecurity = 1
    objXL.Workbooks.Open replace(Wscript.ScriptFullName,».vbs»,».xlsm»)
    objXL.AutomationSecurity = secur
End Sub

[/vba]
Подскажите пожалуйста как закрыть доступ к файлу Запуск.xlsm при его открытии через двойной щелчок мышки. Другими словами чтоб файл запускался только скриптом. СПАСИБО.


Пенсионер

 

Ответить

Gustav

Дата: Вторник, 14.01.2020, 20:10 |
Сообщение № 2

Группа: Друзья

Ранг: Старожил

Сообщений: 2398


Репутация:

986

±

Замечаний:
0% ±


начинал с Excel 4.0, видел 2.1

Наверное, самый простой способ — изменить расширение файла на чужое: например, «.xlsm» — на «.doc». И потом открывайте у себя уже этот «doc»:
[vba]

Код

objXL.Workbooks.Open replace(Wscript.ScriptFullName,».vbs»,».doc»)

[/vba]
Возможно, придется добавить в код пару операторов, подавляющих предупреждения при открытии.


МОИ: Ник, Tip box: 41001663842605

 

Ответить

Nic70y

Дата: Среда, 15.01.2020, 08:43 |
Сообщение № 3

Группа: Друзья

Ранг: Экселист

Сообщений: 8134


Репутация:

1999

±

Замечаний:
0% ±


Excel 2010

сделать файл скрытым
и соот.

К сообщению приложен файл:

4028744.gif
(41.1 Kb)


ЮMoney 41001841029809

Сообщение отредактировал Nic70yСреда, 15.01.2020, 08:44

 

Ответить

boa

Дата: Среда, 15.01.2020, 11:26 |
Сообщение № 4

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365

Egider,
Установите «очень сложный» пароль на открытие файла
и открывайте скриптом
[vba]

Код

Start
Sub Start()
    Dim objXL
    Dim Secur
    Dim sPass
    sPass = «очень сложный пароль»
    On Error Resume Next
    Set objXL = GetObject(, «Excel.Application») ‘ если Excel уже открыт, то присваиваем открытый экземпляр
    If objXL Is Nothing Then Set objXL = CreateObject(«Excel.Application») ‘ иначе, открываем новый
    objXL.Visible = TRUE
    secur = objXL.AutomationSecurity
    objXL.AutomationSecurity = 1
    objXL.Workbooks.Open replace(Wscript.ScriptFullName,».vbs»,».xlsm»), , , , sPass
    objXL.AutomationSecurity = secur
End Sub

[/vba]


Сообщение отредактировал boaСреда, 15.01.2020, 11:37

 

Ответить

Egider

Дата: Среда, 15.01.2020, 14:53 |
Сообщение № 5

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Спасибо Gustav и Nic70y за идеи.
Уважаемый ВОА, пароль установил в раздел Password вкладки Properties — Эта Книга. Все работает. Спасибо.
Сменить пароль понятно как, а как его вообще снять, если отпадет в нем необходимость? Спасибо


Пенсионер

 

Ответить

boa

Дата: Среда, 15.01.2020, 15:01 |
Сообщение № 6

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365

Egider,

так же как и ставили
только новый пароль должен быть пустым


 

Ответить

Egider

Дата: Среда, 15.01.2020, 15:56 |
Сообщение № 7

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Да, я уже понял. Что-то первый раз не получилось. Сейчас все ок.
Единственное, при открытии файла формат листа сверху сдвинут вниз на 2-3 см. Почему?


Пенсионер

 

Ответить

boa

Дата: Среда, 15.01.2020, 16:14 |
Сообщение № 8

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365

при открытии файла формат листа сверху сдвинут вниз на 2-3 см.

shock да ладно,

Excel запоминает последнее отображение

Возможно это следствие работы каких-то ваших макросов…

попробуйте открыть файл, «сдвинуть формат» на место и закрыть Excel.
Повторное открытие должно привести все в порядок yes


Сообщение отредактировал boaСреда, 15.01.2020, 16:24

 

Ответить

Egider

Дата: Среда, 15.01.2020, 19:03 |
Сообщение № 9

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Без скрипта открывается нормально, через скрипт сдвигается. Раскрывал в полный экран, сохранял.
Однако при новом открытии скриптом ничего не меняется. Вновь отступ сверху.???


Пенсионер

 

Ответить

boa

Дата: Среда, 15.01.2020, 21:26 |
Сообщение № 10

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365


а не надо раскрывать в полный экран. Я разве об этом писал?
надо в оконном режиме нстроить вид.
Или тогда уже скриптом раскрывайте на весь экран
[vba]

Код

objXL.WindowState = xlMaximized

[/vba]


 

Ответить

Egider

Дата: Четверг, 16.01.2020, 17:28 |
Сообщение № 11

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Уважаемый boa, уважаемые форумчане — специалисты если есть возможность подскажите пожалуйста:
Возможно-ли использовать скрипт (макрос) для открытия следующего файла с паролем из открытого?
При этом для открытия использовать кнопку. Кнопка есть, работает но при открытии запрашивается пароль.
Как его обойти (что-то прописать в макросе) чтоб файл открывался. И сохранялась функция открытия этого файла
с запросом пароля через двойной клик мышки.


Пенсионер

 

Ответить

boa

Дата: Четверг, 16.01.2020, 19:24 |
Сообщение № 12

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365

[vba]

Код

workbooks.open password:=»123″

[/vba]
а вообще-то в хэлпе все это есть


 

Ответить

Egider

Дата: Пятница, 17.01.2020, 10:16 |
Сообщение № 13

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Извините меня, но объясните куда дописать Вами указанное.
Вот у меня есть макрос кнопки в «файле 1» для открытия другого файла «ПРОБА01», Лист1
[vba]

Код

Sub Открыть_ПРОБА01()
Application.Workbooks.Open(«C:UsersНиколайDesktopЗапуск СкриптомПРОБА01.xlsm»).Worksheets(«Лист1»).Activate
End Sub

[/vba]
Файл «ПРОБА01» имеет пароль 123. Спасибо.


Пенсионер

 

Ответить

Egider

Дата: Пятница, 17.01.2020, 10:34 |
Сообщение № 14

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Добавлю, что задача моя в том, чтобы с кнопки открывать файл «ПРОБА01» без запроса пароля.
А если открывать файл напрямую, то запрашивался чтоб пароль.


Пенсионер

 

Ответить

boa

Дата: Пятница, 17.01.2020, 10:54 |
Сообщение № 15

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365

Egider,
А вы по ссылке заглядывали?
[vba]

Код

Sub Открыть_ПРОБА01()
Application.Workbooks.Open(FileName:=»C:UsersНиколайDesktopЗапуск СкриптомПРОБА01.xlsm», password:=»123″).Worksheets(«Лист1»).Activate
End Sub

[/vba]


 

Ответить

Egider

Дата: Пятница, 17.01.2020, 11:51 |
Сообщение № 16

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

СПАСИБО УВАЖАЕМЫЙ ВОА. Все осознал.


Пенсионер

 

Ответить

Egider

Дата: Пятница, 17.01.2020, 16:38 |
Сообщение № 17

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Простите, но вновь Столкнулся с задачей: У меня 10 листов в открываемом файле, которые открываются своей кнопкой.
И что, нужно теперь для каждого листа в макрос вставлять пароль? Может есть какой-либо выход?


Пенсионер

 

Ответить

RAN

Дата: Пятница, 17.01.2020, 17:20 |
Сообщение № 18

Группа: Друзья

Ранг: Экселист

Сообщений: 5645

Может есть какой-либо выход?

Конечно есть. Снять пароли с листов.


Быть или не быть, вот в чем загвоздка!

 

Ответить

Egider

Дата: Пятница, 17.01.2020, 17:38 |
Сообщение № 19

Группа: Пользователи

Ранг: Новичок

Сообщений: 42


Репутация:

0

±

Замечаний:
0% ±


Excel 2016

Пароль есть только на файле ПРОБА01. На листах его не ставил.


Пенсионер

 

Ответить

boa

Дата: Пятница, 17.01.2020, 18:04 |
Сообщение № 20

Группа: Друзья

Ранг: Ветеран

Сообщений: 543


Репутация:

166

±

Замечаний:
0% ±


2013, 365

Egider, Разделяй и властвуй
[vba]

Код

Option Explicit

Sub Открыть_ПРОБА01()
  Call ActivateSheet(«Лист1»)
End Sub
Sub Открыть_ПРОБА02()
  Call ActivateSheet(«Лист2»)
End Sub

Sub ActivateSheet(sSheetName$)
  Dim sFileName$, oWb As Workbook
  sFileName = «C:UsersНиколайDesktopЗапуск СкриптомПРОБА01.xlsm»
  If IfFileOpened(sFileName) Then Set oWb = Workbooks(sFileName) Else Set oWb = OpenBook(sFileName)
  oWb.Activate
  oWb.Worksheets(sSheetName$).Activate
End Sub

Function OpenBook(sFileName$) As Workbook
  Set OpenBook = Application.Workbooks.Open(FileName:=sFileName, Password:=»123″)
End Function

Function IfFileOpened(sFileName$) As Boolean
    Dim oWb As Workbook
    sFileName = Split(sFileName, PS)(UBound(Split(sFileName, PS)))
    For Each oWb In Workbooks
        If oWb.Name = sFileName$ Then IfFileOpened = True: Exit For
    Next
End Function

Function PS(): PS = Application.PathSeparator: End Function ‘возвращает системный разделитель папок

[/vba]


 

Ответить

Table of Contents

  • Purpose
  • Example Case (Input Excel File)
  • Other Considerations and Further Steps
  • Code Snippet
  • Customize Code to Your Enviornment (Domain, OU, etc.)
  • Execute the Script
  • Sample Output / Results
  • See Also

Purpose

This article explains how to use a VBScript application to read a single-column Excel spreadsheet containing a list of computers, check that list against Active Directory (AD), and then update the spreadsheet with the corresponding computer’s
AD Description field, if present.

In the event the computer does not exist in Active Directory, the Description field on the Excel spreadsheet will be updated with the text «NOT FOUND IN AD.»In the event the computer exists in AD, but the description field in AD is empty, the Description field in the Excel spreadsheet will be updated with the word «BLANK» next to the computer on the list.

Example Case (Input Excel File)

Below is an example of what the initial spreadsheet would look like.

WARNING: DO NOT HAVE EXCEL OPEN – Not even for other spreadsheets during the script run!

In this scenario, the below primary constraints were tested:

1)     
Include 2 valid AD server names with valid descriptions in AD, one with name

2)     
Include 1 valid AD server name, with no description blank, one non-existent server

3)     
Include 1 invalid AD server name

The tested list includes the specific entries listed below:

·        
FileserverA (this would have a description in AD)

·        
FileserverB (no description in AD)

·        
Test (this would have a description in AD)

·        
BrZmN (this would be a non-existent server)

Below is a screen-shot of the initial (pre-script) servers.xlsx document:

Other Considerations and Further Steps

Preferably, delete any other worksheet tabs, so that the only tab remaining is “Sheet1.” Alternatively, you can forego the deletion of other tabs, since this script deals with “Sheet1” only.

Your initial “servers.xlsx” document should contain only the left-most Column 1 populated with your server names and, per the existing script design; your script should be located in your “c:scripts” folder. Alternatively, you may already
have a number of server names with Description fields already filled in. This will not be an issue, since the script automatically will bypass any Excel server record that already contains a non-blank description beside it in Column 2. Therefore, it is acceptable
for your initial spreadsheet already to contain data in Column 2.

Note: You may, if desired, customize the script to have different behavior if Column 2 contains data; i.e., you may wish to have the script always update the Column 2 (Description) field in Excel with the then-current data found in
AD (or with “BLANK” and/or “NOT FOUND IN AD» for each such occurrence).

After you ensure that you have entered the server names into your spreadsheet Column 1 as desired and required; save the following script to your “c:scripts” with the file name “checkservers.vbs.”
(Note: The assumption here is that you know how to open Notepad and paste and save the below code).

Code Snippet

NOTE: Below is only a snippet (portion) of the full code for general understanding. The below code section WILL NOT WORK, unless you click and download/save the code from the embedded links
below or from the «References» section!

The basic premise that the code uses is as follows:
    1) Read through all rows of Col 1 on an Excel document (Main code section)

    2) Read through each AD computer record (Subroutine section)

    3) Update Excel with Description from AD (Main code section)

[Start of Code snippet section]

'-------------------------------------------------------------------------

' Start of MAIN code (checkservers.vbs)

'-------------------------------------------------------------------------

' VBScript: checkservers.vbs

' Author: Jeff Mason aka TNJMAN aka bitdoctor

' 09/06/2013

'

'Basic premise:    1) Read through all rows of Col 1 on an Excel document

'                           2) Read through each AD computer record

'                           3) Update Excel with Description from AD

'Assumptions/Notes:

' 1) Create Excel document (c:scriptsservers.xlsx) with ONE worksheet,

'    containing only "server name" in Column 1

‘Other assumptions in the FULL SCRIPT, download now

' Assumptions:

' You must Set excelPath = "C:scriptsservers.xlsx" (or wherever your xlsx file is)

' You must have at least "read" permissions to AD/LDAP

'

Option
Explicit

Dim
objExcel

Dim
excelPath

Dim
worksheetCount

Dim
counter                                                      
' To count rows and/or columns

Dim
currentWorkSheet

‘…

excelPath =
"C:scriptsservers.xlsx"

‘Full code is listed in the FULL SCRIPT, download now

WScript.Echo
"Reading Data from Path/File: "
& excelPath

Set
objExcel = CreateObject("Excel.Application")

objExcel.DisplayAlerts = 0
' Don't display any messages about conversion and so forth

WScript.Echo
"-------------------------------------------------------"

WScript.Echo
"Reading data from worksheet "
& workSheetCount

WScript.Echo
"-------------------------------------------------------" 
& vbCRLF

Set
currentWorkSheet = objExcel.ActiveWorkbook.Worksheets(workSheetCount)

' What is the leftmost column in the spreadsheet that has data in it

left = currentWorksheet.UsedRange.Column

Set
Cells = currentWorksheet.Cells

'-----------------------------------------------------------------------------

' Row Loop - Loop through each row in the worksheet (but only for Column 1)

'

' Only deal with Cols 1 & 2 of Sheet1, since SERVER=Col1 and DESCRIPTION=Col2

' Column 2 is built by "checksvr" subroutine, based on Column 1)

'

  For
row = 0 to (usedRowsCount-1)

  ' only look at rows/cols in the "used" range

    curRow = row+top

'   curCol = column+left

    If
IsEmpty(strDescription) Then
' If Col 2 already populated, skip to next row in sheet

      If
Not
(IsEmpty(server))
Then

‘Full code is listed in the FULL SCRIPT, download now

      End
If

    End
If

  Next

'

' End Row loop

'-----------------------------------------------------------------------------

' Done with the current worksheet, release the memory

Set
currentWorkSheet = Nothing

‘Save and close the workbook - Full code is listed in the FULL SCRIPT, download now

WScript.Echo
"Finished."

Set
currentWorkSheet = Nothing

' Finished with Excel object, release it from memory & get out !!!

Set
objExcel = Nothing

WScript.Quit(0)

'-------------------------------------------------------------------------

' End of MAIN code

'-------------------------------------------------------------------------

'-------------------------------------------------------------------------

' Subroutine (checksvr) to check for the sever name in Active Directory

'-------------------------------------------------------------------------

'

Sub
checksvr(svr)

On
Error
Resume
Next

' Point to the domain/ldap root

' Query all Active Directory (normally, leave this commented, query specific OU(s)

' strRoot = objRootDSE.Get("DefaultNamingContext") 'Uncomment to search ENTIRE AD TREE

' Query a specific Organizational Unit

strRoot =
"OU=Servers,DC=YOUR-DOMAIN,DC=com"
' Comment this out, if searching ALL OF AD

‘…

 objCn.Provider =
"ADsDSOObject"

objCn.Open
"Active Directory Provider"

' Filter the query for only sAMAccountName,description of any computers in AD

objCmd.commandtext = …

‘…

svrcmp = UCase(svr) &
"$" 'Upper-case the Server entry from the spreadsheet for consistent compare

svrflag =
"" 'Clear out the "found-server" flag

Do
While
Not
objRes.EOF

' If description is blank/null, set the value to the word "BLANK"

    strDescription =
""

    If
Not
(IsNUll(objRes.Fields(
"description").Value))
Then

       ‘ …

‘Full code is listed in the FULL SCRIPT, download now

     ' We want to check ALL descriptions, including null descriptions

    ' But only for the server passed into this script as an argument

    If
svrcmp = objRes.Fields("sAMAccountName").Value
Then

     'If Excel server name found in AD, set svrflag = "TRUE" & end the subroutine

      svrflag =
"TRUE"

     'Write this to the Excel spreadsheet / exit the subroutine

      Exit
Sub

    End
If

   'Move to / read the next AD resource record

    objRes.MoveNext

Loop

   'If flag never set to "TRUE" then fall out through here - server not found in AD

    strDescription =
"NOT FOUND IN AD"

objRes.close

ObjCn.close

'-------------------------------------------------------------------------

 End
Sub

'-------------------------------------------------------------------------


[End of Code snippet section]

Customize Code to Your Enviornment (Domain, OU, etc.)

You must edit the full code and customize the “strRoot” variable in the script to match your own AD environment.
Caution: Take care to modify only the 2nd “strRoot” line, since the 1st strRoot line is commented out.
In the script, a generic line is included (strRoot = «OU=Servers,DC=YOUR-DOMAIN,DC=com«); this is the only line that should need to be customized, before saving your script.

As an example, if your domain is “contoso.com,” and your servers are located in the “Servers” Organizational Unit (OU), then the requisite modified “strRoot” line would look like the following:

strRoot = «OU=Servers,DC=contoso,DC=com«

After modifying the “strRoot” line to match your AD environment, save the modified script as “c:scriptscheckservers.vbs.”

Execute the Script

Next, invoke a command shell from your Windows workstation computer: Click “Start,“ then type “cmd” and press Enter. This will invoke the Windows Command Shell (often called the DOS Command Prompt).

Change your working directory to your scripts folder and execute the “checkservers.vbs” script (i.e., type “cscript checkservers.vbs” and press Enter):

Sample Output / Results

Following is the output from a live run of the “checkservers.vbs” script, followed by the spreadsheet after the updates applied by the script:

c:scripts>cscript checkservers.vbs

Microsoft (R) Windows Script Host Version 5.8

Copyright (C) Microsoft Corporation. All rights reserved.

Reading Data from Path/File: C:scriptsservers.xlsx

——————————————————-

Reading data from worksheet 1

——————————————————-

Finished.

c:scripts>


After executing the “checkservers.vbs” script against the “servers.xlsx” initial spreadsheet, below is a screen-shot of the resultant, updated “servers.xlsx” spreadsheet:

Note: The script found a description for the first computer name, “FileserverA,” in AD and updated line 1 with the description, “Main file server.” The script found that “FileserverB” existed in AD, but had an empty Description
field, thus the script updated the spreadsheet with the word “BLANK.” The script bypassed checking the computer named “Test,” because the spreadsheet already contained a description entry for that computer. The script did not find an entry for computer “BrZmN,”
thus the script updated the spreadsheet with the phrase, “NOT FOUND  IN AD.”


See Also

The
above-referenced TechNet published script can be obtained from above embedded links or from the following link:
http://gallery.technet.microsoft.com/scriptcenter/VBScript-to-read-Excel-ce3bff05

Base code for parsing through AD was found here:
Mr. Gregory Shiro’s script for parsing AD was found in TechNet forums (used for subroutine):
http://tinyurl.com/ljwjfwe

— VBA & VBS Portal

— Wiki: Portal of TechNet Wiki Portals

I am writing a small VBScript to do the following:

  1. Check if Excel is open; if not open it.
  2. If Excel is open, check if a specific workbook is open.
  3. If workbook is open, make it active; if not, open it.

So far I have been able to write the following code:

ExcelFileName = "....xlsx"

On Error Resume Next
Set xl = GetObject(, "Excel.Application")
IF Err Then
    If Err.Number = 429 Then
    WScript.Echo "Workbook not open (Excel is not running)."
    Else
    WScript.Echo Err.Description & " (0x" & Hex(Err.Number) & ")"
    End If
    WScript.Quit 1
End If
On Error Goto 0

Set wb = Nothing
For Each obj In xl.Workbooks
    If obj.Name = ExcelFileName Then
    Set wb=obj
    xl.DisplayAlerts = False
    wb.Save
    Exit For
    End If
Next

If wb Is Nothing Then
    xl.Workbooks.Open("C:...")
End If

Set xl = Nothing
Set wb = Nothing

But if Excel is not already open, it silently fails to open a new instance.

Nathan Tuggy's user avatar

Nathan Tuggy

2,23427 gold badges30 silver badges38 bronze badges

asked May 9, 2015 at 1:07

Christoph Fetkenheuer's user avatar

5

Use GetObject to open the file.

set wb = GetObject("c:folderexcel.xls")

COM will work out what needs to be done. That one line is all you need for your three requirements.

This is the guts of what VB asks COM to do when using GetObject with a filename.

BindMoniker

Locates an object by means of its moniker, activates the object if it is inactive, and retrieves a pointer to the specified interface on that object.

HRESULT BindMoniker(
LPMONIKER pmk,
DWORD grfOpt,
REFIID iidResult,
LPVOID FAR * ppvResult
);

answered May 10, 2015 at 4:39

1

GetObject behaves normally in giving you a running instance of Excel or causing an error. In case you get an error (Excel not running), use CreateObject to create a new instance of Excel.

answered May 9, 2015 at 1:42

Tarik's user avatar

TarikTarik

10.7k1 gold badge24 silver badges40 bronze badges

Понравилась статья? Поделить с друзьями:
  • Vbs open excel file
  • Vbs excel save as
  • Vbs createobject excel application
  • Vbnewline in excel vba
  • Vbe6ext olb could not be loaded что делать excel