vbscript syntax error saving a excel file - vbscript

I have my code in vb script. result of a stored procedure is saved in an excel.I'm getting error in line saying
TITLE: ActiveX Script Task
Error Code: 0
Error Source= Microsoft VBScript compilation error
Error Description: Syntax error
Error on Line 97
-----------------this is the code pls help..
Dim oFSOExcelFile
Set oFSOExcelFile= CreateObject("Scripting.FileSystemObject")
Dim workSheet,sFileName
Dim iRow,headingRow
'Create the Excel workbook
On error Resume Next
Set oXLIDRenewal = CreateObject("Excel.Application")
oXLIDRenewal.Visible=True
With oXLIDRenewal
'Make sure there is no minimized window.
.Application.Visible = False
.Application.DisplayAlerts = False
End With
If not rstRev.EOF then
'Name of the excel File to import to.
sFileName=''D:\packages\Rev&CPExcel\Rev'' &iday &''-''&imonth ''-''&iyear &''.xls''
'Delete the Excel File if it already exists.
If oFSOExcelFile.FileExists(sFileName) Then
On Error Resume Next
oFSOExcelFile.DeleteFile(sFileName)
End If

Your
sFileName=''D:\packages\Rev&CPExcel\Rev'' &iday &''-''&imonth ''-''&iyear &''.xls''
uses the wrong quotes and lacks at least one &. So try:
sFileName = "D:\packages\Rev&CPExcel\Rev" & iday & "-" & imonth & "-" & iyear & ".xls"
Double check ..\Rev&CPExcel\..

Related

vbs(25, 3) Microsoft VBScript runtime error: Invalid procedure call or argument

I wrote a script to grab the list for folders from a file and it will check and delete for files that are more than 90 days old.
The script was able to delete the files older than 90 days. However I keep on getting an error saying:
D:\cleanup90days.vbs(25, 3) Microsoft VBScript runtime error: Invalid procedure call or argument
I don't have an idea what I have missed. Any help will be appreciated.
Below is my script:
Dim days
Dim inputFolderList, ObjFolder, Files, objFileAge
If Not WScript.Arguments.Count = 2 Then
Wscript.Echo "Invalid number of arguments. Arg1: Daily or Weekly. Arg2: Remove all files older then this"
WScript.Quit(-1)
End If
days = WScript.Arguments.Item(1)
inputFileList = "D:\FileGrep2.txt"
Set Fso = CreateObject("Scripting.FileSystemObject")
Set objTextFile = fso.OpenTextFile(inputFileList, 1)
Do Until objTextFile.AtEndOfStream
sFolderName = objTextFile.ReadLine
getfoldernames(sFolderName)
Loop
Function getfoldernames(sFolderName)
Set ObjFolder = fso.GetFolder(sFolderName)
Set Files = ObjFolder.Files
For Each Check In Files
objFileAge = DateDiff("n", Check.DateLastModified, Now)
If objFileAge > 90 Then
WScript.Echo Now & "the following will be deleted " & Check.Path
Check.Delete
End If
Next
End Function
Probably, you've got an empty line in your input file "D:\FileGrep2.txt" causing the Set ObjFolder = fso.GetFolder(sFolderName) line throwing this error.

Loop all the rows of a worksheet and copy them into a blank sheet

I'm facing a serious problem while importing my script into UFT for more than 2 weeks, I tried everything. As a worarround, I'm cpying the workbook and then I import the new on but this sometimes doesn't work too.
this is my code:
DataTable.ImportSheet workbook1,"name1","sheet1"
this is my workarround:
On error resume next
DataTable.ImportSheet workbook_path,"name1","sheet1"
MsgBox "Error: " & Err.Number & " (" & Err.Source & ") - " & Err.Description
If Err.Number <> 0 Then
If err.number = 20012 Then
Set objExcel1 = CreateObject("Excel.Application")
objExcel1.Visible = False
objExcel1.DisplayAlerts=False
Dim RelativePath
RelativePath = "C:\xyz\new_workbook.xls"
Dim objSheet1
Set objWorkbook1= objExcel1.Workbooks.Open("workbook.xls")
Set filesys = CreateObject("Scripting.FileSystemObject")
If filesys.FileExists(RelativePath) Then
filesys.DeleteFile RelativePath
End If
Set objWorkbook2=objExcel1.Workbooks.Add
objWorkbook2.saveAs RelativePath
For each objsheet1 in objworkbook1
objworkbook2.AddSheet objsheet1.Name
objsheet1.copy objworkbook2.sheets(1)
Next
objWorkbook2.save
objworkbook1.close
objworkbook2.close
objExcel1.Quit
Set objSheet1 = Nothing
Set objWorkbook1 = Nothing
Set objWorkbook2 = Nothing
Set objExcel1 = Nothing
On error resume next
DataTable.ImportSheet RelativePath,"name1","sheet1"
MsgBox "Error: " & Err.Number & " (" & Err.Source & ") - " & Err.Description
End if
End If
I want to try looping all the rows of the sheets and copying them into the new ones instead of copying them directly. Any help please ? if anyone has other solution to solve this issue, pleeeeeeease help
Why loop through the rows if you want them all? Just copy the sheet. IF you need the code for that, fire up the macro recorder, copy the sheet and stop the macro recorder.
Change your DataTable.ImportSheet workbook1,"name1","sheet1" call to DataTable.ImportSheet workbook1,"name1","Action1" or to DataTable.ImportSheet workbook1,"name1","Global". Make sure that your path is correct for the workbook and name1 sheet exists in your workbook
Are you able to import manually into DataTable? Sometimes, the special characters from the spreadsheet throw error.
If you are receiving "Invalid file error", follow the steps.
1. Open UFT and Activate Data Table and Perform the below action
Perform
Choose the appropriate sheet to be imported.
Check if any "Invalid File Error Dialog". If yes Goto Step 5 else GoTo Step 2
Go back to actual spreadsheet and replace all of the special characters including spaces and clear all the Formatting of the cells

VBA excel : Using WScript to run bat file

I am using the following VBA code to run a bat file. It was an example to run the note pad application instead of .bat file.
While running I am getting an error "Method run of object ISshShell3 failed"
Please let me know how can i use it to run the bat file from a desired directory?
My aim is to run a command on console and wait for the command to finish.
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
errorCode = wsh.Run("D:\test.bat", windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
Thanks in advance

How can I determine if a file is locked using VBS?

I am writing a VB Script to update some files on the network. Before beginning, I want to know if any of the files are locked. I'd like to do this before I actually do any updates.
I am aware that I can handle the error if the file is locked when I try to replace it, but I really want to know if any files are locked before I start updating any files.
Is there any way to see that a file is locked using VBS (apart from trying to replace it)?
This function determines whether a file of interest can be accessed in 'write' mode. This is not exactly the same as determining whether a file is locked by a process. Still, you may find that it works for your situation. (At least until something better comes along.)
This function will indicate that 'write' access is not possible when a file is locked by another process. However, it cannot distinguish that condition from other conditions that prevent 'write' access. For instance, 'write' access is also not possible if a file has its read-only bit set or possesses restrictive NTFS permissions. All of these conditions will result in 'permission denied' when a 'write' access attempt is made.
Also note that if a file is locked by another process, the answer returned by this function is reliable only at the moment the function is executed. So, concurrency problems are possible.
An exception is thrown if any of these conditions are found: 'file not found', 'path not found', or 'illegal file name' ('bad file name or number').
Function IsWriteAccessible(sFilePath)
' Strategy: Attempt to open the specified file in 'append' mode.
' Does not appear to change the 'modified' date on the file.
' Works with binary files as well as text files.
' Only 'ForAppending' is needed here. Define these constants
' outside of this function if you need them elsewhere in
' your source file.
Const ForReading = 1, ForWriting = 2, ForAppending = 8
IsWriteAccessible = False
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Dim nErr : nErr = 0
Dim sDesc : sDesc = ""
Dim oFile : Set oFile = oFso.OpenTextFile(sFilePath, ForAppending)
If Err.Number = 0 Then
oFile.Close
If Err Then
nErr = Err.Number
sDesc = Err.Description
Else
IsWriteAccessible = True
End if
Else
Select Case Err.Number
Case 70
' Permission denied because:
' - file is open by another process
' - read-only bit is set on file, *or*
' - NTFS Access Control List settings (ACLs) on file
' prevents access
Case Else
' 52 - Bad file name or number
' 53 - File not found
' 76 - Path not found
nErr = Err.Number
sDesc = Err.Description
End Select
End If
' The following two statements are superfluous. The VB6 garbage
' collector will free 'oFile' and 'oFso' when this function completes
' and they go out of scope. See Eric Lippert's article for more:
' http://blogs.msdn.com/b/ericlippert/archive/2004/04/28/when-are-you-required-to-set-objects-to-nothing.aspx
'Set oFile = Nothing
'Set oFso = Nothing
On Error GoTo 0
If nErr Then
Err.Raise nErr, , sDesc
End If
End Function
The script below tries to write to a file for 30 seconds and gives up after that. I needed this when all our users had to click on a script. Chances are that multiple users try to write at the same time. OpenCSV() tries to open the file 30 times with a delay of 1 second in between.
Const ForAppending = 8
currentDate = Year(Now) & "-" & Month(Now) & "-" & Day(Now) & " " & Hour(Now) & ":" & Minute(Now) & ":" & Second(Now)
filepath = "\\network\path\file.csv"
Set oCSV = OpenCSV( filepath )
oCSV.WriteLine( currentDate )
oCSV.Close
Function OpenCSV( path )
Set oFS = CreateObject( "Scripting.FileSystemObject" )
For i = 0 To 30
On Error Resume Next
Set oFile = oFS.OpenTextFile( path, ForAppending, True )
If Not Err.Number = 70 Then
Set OpenCSV = oFile
Exit For
End If
On Error Goto 0
Wscript.Sleep 1000
Next
Set oFS = Nothing
Set oFile = Nothing
If Err.Number = 70 Then
MsgBox "File " & filepath & " is locked and timeout was exceeded.", vbCritical
WScript.Quit
End If
End Function
Or, more simply:
Assuming you already have a variable in your VBS named FileName, which contains the full filepath you want to test:
Dim oFso, oFile
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oFile = oFso.OpenTextFile(FileName, 8, True)
If Err.Number = 0 Then oFile.Close
Line 3 tries to open the file you want to test with append permissions enabled. e.g. it attempts to open the file with a write lock.
If opening the file with a write lock generates an error, then your VBS will error on the third line and not continue. At that point your error handling from wherever you called the VBS should kick in. The error message will be "Permission Denied" if you couldn't get a write lock.
If opening the file with a lock doesn't result in an error, then line 4 closes it again. You can now open the file or do whatever you want with it, confident that it doesn't have a write lock on it.

What the win cmd to open a particular spreadsheet in Excel?

I know that you can open an Excel file from the win cmd line. But how would you open a particular spreadsheet in that file using win cmd?
Paste the following code into a text editor (NotePad, WordPad, Word
etc)
Save the file with a "vbs" extension, for example
ExcelSheet2.vbs
Change this line strFileName = "c:\temp\testa.xlsx" to your
desired Excel file path
You can then run this from the commandline by entering the path name of your vbs file
The code has error handling in case the filepath is wrong, or a second sheet isn't present.
[Updated: added further error handling to test for the second sheet being hidden]
Const xlVisible = -1
Dim objExcel
Dim objWb
Dim objws
Dim strFileName
strFileName = "c:\temp\test.xlsx"
On Error Resume Next
Set objExcel = CreateObject("excel.application")
Set objWb = objExcel.Workbooks.Open(strFileName)
Set objws = objWb.Sheets(2)
On Error GoTo 0
If Not IsEmpty(objws) Then
If objws.Visible = xlVisible Then
objExcel.Goto objws.Range("a1")
Else
wscript.echo "the 2nd sheet is present but is hidden"
End If
objExcel.Visible = True
Else
objExcel.Quit
Set objExcel = Nothing
If IsEmpty(objWb) Then
wscript.echo strFileName & " not found"
Else
wscript.echo "sheet2 not found"
End If
End If
Alternatively you could open the workbook from the command line and add the below code to the Workbook to activate "Sheet2"
Private Sub Workbook_Open()
ThisWorkbook.Sheets("Sheet2").Activate
End Sub
You will need to make sure the workbook is in a trusted location and security settings allow the macro to run. #brettdj's solution is much superior but this is an alternative.

Resources