Доброго всем дня. Очень надеюсь, что среди знатоков есть специалисты по данному языку.
Проблема у меня следующая. Требуется в 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
‘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
‘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 |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
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
ResumeNext
' 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
NotobjRes.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:
- Check if Excel is open; if not open it.
- If Excel is open, check if a specific workbook is open.
- 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
2,23427 gold badges30 silver badges38 bronze badges
asked May 9, 2015 at 1:07
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
TarikTarik
10.7k1 gold badge24 silver badges40 bronze badges