How to delete excel sheet from UFT - hp-uft

I am trying to write a function which will delete all sheets except the one passed as parameter. Below function is being called but function does not delete any sheets. How can I delete all worksheets except one?
........
Set ExcelObj = createobject("excel.application")
ExcelObj.Visible = true
Set ConfigFile = ExcelObj.Workbooks.Open (FilePath)
Set ConfigSheet = ConfigFile.Worksheets("Scripts")
Set ConfigApplicationSheet = ConfigFile.Worksheets("Applications")
Set ExecutiveSummarySheet = ConfigFile.Worksheets("Summary")
ExcelObj.ActiveWorkBook.SaveAs SummaryFilePath
DeleteSheet "ConfigScripSheet","Summary"
Function DeleteSheet(ConfigSheet,mySheetname)
'Writing Name and Path of each File to Output File
For Each ObjFile In ObjFiles
ObjOutFile.WriteLine(ObjFile.Name & String(50 - Len(ObjFile.Name), " ") & ObjFile.Path)
Next
ObjOutFile.Close
DeleteSheet = 0
ExcelObj.DisplayAlerts = False
For Each objWorksheet In ConfigSheet.Worksheets
If not objWorksheet.Name = mySheetname Then
DeleteSheet = 1
ConfigScripSheet.sheets(objWorksheet.Name).Select
ConfigScripSheet.sheets(objWorksheet.Name).Delete
ExcelObj.DisplayAlerts = False
End If
Next
End Function

Trying to correct your code above was too much of a minefield for me as I couldn't tell what you meant in several places - so I rewrote it based on what you had said in the description was your goal.
The code below will open the file, associate the objects the way you had them, pass the workbook object and a sheet name not to be deleted into the DeleteSheet function, which will delete any sheet in the workbook that is not named as per the passed in parameter SheetNameNotToDelete
Let me know if any of the code is unclear.
Option Explicit ' Forces declaration of variables
Dim FilePath, SummaryFilePath '<-- Need set to some value!
FilePath = ""
SummaryFilePath = ""
Dim ExcelObj : Set ExcelObj = CreateObject("Excel.Application")
Dim ConfigFile : Set ConfigFile = ExcelObj.Workbooks.Open(FilePath)
Dim ConfigSheet : Set ConfigSheet = ConfigFile.Worksheets("Scripts")
Dim ConfigApplicationSheet : Set ConfigApplicationSheet = ConfigFile.Worksheets("Applications")
Dim ExecutiveSummarySheet : Set ExecutiveSummarySheet = ConfigFile.Worksheets("Summary")
ExcelObj.ThisWorkbook.SaveAs SummaryFilePath
DeleteSheet ConfigFile, "Summary"
Function DeleteSheet(ByRef WorkbookObj, ByVal SheetNameNotToDelete)
Dim oWorksheet
For Each oWorksheet In WorkbookObj.Worksheets
If oWorksheet.Name <> SheetNameNotToDelete And WorkbookObj.Worksheets.Count >=2 Then
oWorksheet.Delete ' Excel won't let you delete all worksheets from a workbook
End If ' the check on Count >=2 covers the case where no worksheet exists
Next ' called "Summary" to be left
End Function

Related

Python to VBScript conversion

I need to help in converting a Python script to VBScript. I'm trying to load the .cal file as a binary value file and edit a particular value in the file but unfortunately, my environment only supports VBScript.
import argparse
parser = argparse.ArgumentParser(description='Sapix Cal File Sensitivity Adjustment')
parser.add_argument("-calfile", default="test.cal", help="Enter the Calfile name (ex: 09781DK5081.cal")
parser.add_argument("-vtest", default=125, help="New Vtest setting (85-205)")
parser.add_argument("-vref", default=250, help="New Vref setting (250-120)")
args = parser.parse_args()
calfile = args.calfile
vtest = args.vtest
vref = args.vref
print(calfile)
print(vtest)
print(vref)
with open(calfile, "rb") as binary_file:
# Read the whole file at once
data = bytearray(binary_file.read())
# Find Line with VTEST setting
ivteststart = data.find(bytearray('PARALLEL_VOLTAGE_TEST', 'utf-8'))
ivtestend = data.find(b'\n',ivteststart)
# Remove original VTEST line
del data[ivteststart:ivtestend+1]
# Insert New Line with new VTEST
new_vtest = bytearray("PARALLEL_VOLTAGE_TEST %s\n" % (vtest),'utf-8')
data[ivteststart:ivteststart] = new_vtest
# Find Line with VREF setting
ivrefstart = data.find(bytearray('PARALLEL_VOLTAGE_REF', 'utf-8'))
ivrefend = data.find(b'\n',ivrefstart)
# Remove original VREF line
del data[ivrefstart:ivrefend+1]
# Insert New Line with new VREF
new_vref = bytearray("PARALLEL_VOLTAGE_REF %s\n" % (vref),'utf-8')
data[ivrefstart:ivrefstart] = new_vref
# Write new sensitivity settings to cal file
with open(calfile, "wb") as binary_file:
binary_file.write(data)
I was able to make the changes if I load the file as text file but I have no clue how to load the same as Binary value and make the changes
Option Explicit
Dim objFso, objFolder, objFile, objOtF, cd, content
Dim targetDir
targetDir = "C:\Kiosk\UI"
Dim objRegExp
Set objRegExp = New RegExp
objRegExp.Pattern = "\bPARALLEL_VOLTAGE_TEST \d+\b"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(targetDir)
For Each objFile in objFolder.Files
If LCase(Right(objFile.Name, 4)) = ".cal" Then
cd = objFile.Name
Set objOtF = objFso.OpenTextFile(cd, 1)
content = objOtF.ReadAll
objOtF.Close
Set objOtF = objFso.OpenTextFile(cd, 2)
objOtF.Write objRegExp.Replace(content, "PARALLEL_VOLTAGE_TEST 230")
objOtF.Close
Dim objRegExp1
Set objRegExp1 = New RegExp
objRegExp1.Pattern = "\bPARALLEL_VOLTAGE_REF \d+\b"
Set objOtF = objFso.OpenTextFile(cd, 1)
content = objOtF.ReadAll
objOtF.Close
Set objOtF = objFso.OpenTextFile(cd, 2)
objOtF.Write objRegExp1.Replace(content, "PARALLEL_VOLTAGE_REF 190")
objOtF.Close
End If
Next
Take a look at the following post: Read and write binary file in VBscript. You might be able to use ADODB.Stream to read and write binary data. Other approaches are explored also, including reading characters one by one into an array.
Here's the code from that post:
Function readBinary(strPath)
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFile: Set oFile = oFSO.GetFile(strPath)
If IsNull(oFile) Then MsgBox("File not found: " & strPath) : Exit Function
With oFile.OpenAsTextStream()
readBinary = .Read(oFile.Size)
.Close
End With
End Function
Function writeBinary(strBinary, strPath)
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
' below lines pupose: checks that write access is possible!
Dim oTxtStream
On Error Resume Next
Set oTxtStream = oFSO.createTextFile(strPath)
If Err.number <> 0 Then MsgBox(Err.message) : Exit Function
On Error GoTo 0
Set oTxtStream = Nothing
' end check of write access
With oFSO.createTextFile(strPath)
.Write(strBinary)
.Close
End With
End Function

Converting PPT file to PDF

I have a macro which opens a PowerPoint file stored on the workbook and then modifies it using the below code
Set PApp = CreateObject("PowerPoint.Application")
PApp.Visible = True
Pth = ThisWorkbook.Path
ErrorPopUp = True
Dim TsyTemplate As Object
Set TsyTemplate = ThisWorkbook.Sheets("Report Templates").OLEObjects(“Report 1”)
TsyTemplate.Copy
Sheets("Version Control").Paste
Set TsyTemplate = ThisWorkbook.Sheets("Book 1").OLEObjects(1)
TsyTemplate.Verb Verb:=xlOpen
Set TsyTemplate = Nothing
Set PPres = PApp.ActivePresentation
This works fine however I want to add some code which then converts the open PowerPoint file into a PDF file. I would prefer it to just convert it without saving it somewhere but I don't believe this is possible so I am using he below code to save it as a PDF FILE
PDFName = ActiveWorkbook.Path & "/test.pdf"
PPres.ExportAsFixedFormat Path:=PDFName, FixedFormatType:=ppFixedFormatTypePDF, RangeType:=ppPrintSelection
This isn't working though as I get the error message "type mismatch"
Does anyone have any suggestions as to what I am doing wrong.
Thanks
Full code:
Global PApp As Object
Global PPres As Object
Global PPTFileName As String
Global ppFixedFormatTypePDF As Long
Global ppPrintSelection As Long
Sub Test_Printing_To_PDF()
Set PApp = CreateObject("PowerPoint.Application")
PApp.Visible = True
Pth = ThisWorkbook.Path
ErrorPopUp = True
Dim TsyTemplate As Object
Set TsyTemplate = ThisWorkbook.Sheets("Report Templates").OLEObjects("Report 1")
TsyTemplate.Copy
Sheets("Version Control").Paste
Set TsyTemplate = ThisWorkbook.Sheets("Version Control").OLEObjects(1)
TsyTemplate.Verb Verb:=xlOpen
Set TsyTemplate = Nothing
Set PPres = PApp.ActivePresentation
PPres.Slides(1).Shapes("Presentation_Title").TextFrame.TextRange.Text = "Test printing code"
ppFixedFormatTypePDF = 2
ppPrintSelection = 2
PDFName = ActiveWorkbook.Path & "/test.pdf"
PPres.ExportAsFixedFormat Path:=PDFName, FixedFormatType:=ppFixedFormatTypePDF, RangeType:=ppPrintSelection
End Sub
I removed some of your Excel code so that I could try this here; since it seems to have nothing to do with the PDF export from PPT, shouldn't make any difference. New (working) code below with comments:
Option Explicit
Global PApp As Object
Global PPres As Object
Global PPTFileName As String
Global ppFixedFormatTypePDF As Long
Global ppPrintSelection As Long
Const ppSaveAsPDF As Long = 32
Sub Test_Printing_To_PDF()
' Always include Option Explicit and DIM all variables
Dim Pth As String
Dim ErrorPopUp As Boolean
Dim PDFName As String
Set PApp = CreateObject("PowerPoint.Application")
PApp.Visible = True
Pth = ThisWorkbook.Path
ErrorPopUp = True
' Just invoking PowerPoint doesn't necessarily create a presentation.
' You need to add one (or open an existing one)
Set PPres = PApp.presentations.Add
' And creating a new presentation doesn't necessarily add slides so:
PPres.slides.Add 1, 1
' Unless you've opened a presentation that happens to have a shape named
' Presentation_Title on the first slide, this will fail:
'PPres.slides(1).Shapes("Presentation_Title").TextFrame.TextRange.Text = "Test printing code"
' So I've changed it to this:
PPres.slides(1).Shapes(1).TextFrame.TextRange.Text = "Test printing code"
' / isn't a valid character:
'PDFName = ActiveWorkbook.Path & "/test.pdf"
' so I changed it to this:
PDFName = ActiveWorkbook.Path & "\test.pdf"
' And there are all sorts of reports all over the net about
' the Export routine being buggy. Substitute this and it works:
PPres.SaveAs PDFName, ppSaveAsPDF
End Sub

Script works on its own but not as a subroutine of a bigger program

I have written the following code, tested it, and it works. I then literally copied and pasted it into a larger program as a sub. I'm getting a Type mismatch on the Split Function now. I copied & pasted it out of the subroutine and into a new file and it works again. Any help on why this is happening would be appreciated.
Dim oFSO
Dim oNew
Dim oExcel
Dim Folder2
Dim oFile
Dim File, Line
Dim f, fc
Dim x, y, e, i, j
Dim objSheet, TFile, TSheet
Dim TextLine
'Calls Excel into session and leaves it running in the background
Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = False
oExcel.DisplayAlerts = False
'Opens the selected excel file and then lets the user choose the folder to be updated to it
Set oNew = oExcel.Workbooks.Open(BrowseForFolder("Select Excel File to Update"))
Set oFSO = CreateObject("Scripting.FileSystemObject")
Folder2 = BrowseForFolder("Choose file containing updated CSV's")
Set f = oFSO.GetFolder(Folder2)
Set fc = f.Files
oNew.Activate
'This loops through every file in the folder, compares the name of the file to the names
'of the sheets in the excel file and overwrites the data to on the spreadsheet
For Each oFile In fc
TFile = Left(oFile.Name,InStr(oFile.Name,"-")-1)
For i =1 To oNew.Sheets.Count
j = InStr(oNew.Sheets(i).Name,"-")-1
TSheet = Left(oNew.Sheets(i).Name,j)
if TSheet = TFile Then
oNew.Sheets(i).Activate
set objSheet = oNew.ActiveSheet
objSheet.Name = Left(oFile.Name,InStr(oFile.Name,".")-1)
Set File = oFSO.OpenTextFile(oFile)
x = 1
Do While File.AtEndofStream <> True
Line = File.Readline
TextLine = Split(Line,",")
y = 1
For Each e In TextLine
objSheet.Cells(x, y) = e
y = y+1
Next
x=x+1
Loop
End If
Next
Next
MsgBox "Spreadsheet Updated! New spreadsheet is located in Documents"
' Save merged result as an Excel file in Documents
oNew.SaveAs "SAPDASHBOARD", 51
oNew.Close
' Shut down Excel
oExcel.Quit
Set oExcel = Nothing
Set oNew = Nothing
Set oFile = Nothing
Function BrowseForFolder(title)
Dim shell : Set shell = CreateObject("Shell.Application")
Dim file : Set file = shell.BrowseForFolder(0, title, &H4000,0)
If file is Nothing Then
WScript.Echo "No Folder Selected"
WScript.Quit
End IF
BrowseForFolder = file.self.Path
End Function
I actually figured it out. The problem wasn't this portion of the script, it was the fact that one of the other subroutines in the big program was named Split. So when it tried to run the builtin function "Split" it tried to call the subroutine. That's a mistake I won't be making again

Find and Replace?

Does anyone know of a way to do a more complex find and replace? For example, I have many documents with merge fields. I need to be able to change the merge fields in these documents based on a list of definitions\translations. So in this example lets say I have 100 equipment leases created in M$ word saved as .dot. Each one the following merge fields exists, and I want to change them all at once to a new value as shown below.
{MERGEFIELD state} -> {MERGEFIELD ownerstate}
{MERGEFIELD city} -> {MERGEFIELD ownercity}
{MERGEFIELD zip} -> {MERGEFIELD ownerzip}
It's not so important that I be able to edit more than 1 document at a time than it is that I be able to make multiple edits at once.
OK so I was able to create a solution to my own issue. To do this I created the following code to do a find and replace based on a definition list in excel.
Option Explicit
Private MyXL As Object
Sub Test()
Dim WB As Excel.Workbook, WS As Excel.Worksheet, MyDefTbl As Excel.Range, MyRow As Excel.Range
Dim MySearchRng As Excel.Range, ReplacementRng As Excel.Range
Dim myDoc As Document
Call MyInitializeOfficeApps
'Define the Workbook that contains the Definitions
Set WB = MyXL.Workbooks.Open("E:\MailMerges\Definitions\Equip.xlsx")
'Define the Woksheet that contains the Definition list
Set WS = WB.Worksheets("Sheet1")
'Define the Range name that defines the Definition list
Set MyDefTbl = WS.Range("MyDefs")
'Define the Document to be changed
Set myDoc = ActiveDocument
For Each MyRow In MyDefTbl.Rows
Set MySearchRng = WS.Cells(MyRow.Row, 1)
Set ReplacementRng = WS.Cells(MyRow.Row, 2)
'MsgBox MySearchRng & "====>" & ReplacementRng
myDoc.Select
With Selection.Find
.Text = " MERGEFIELD " & MySearchRng.Text
.Replacement.Text = " MERGEFIELD " & ReplacementRng.Text
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Next MyRow
Set MyDefTbl = Nothing
Set MyRow = Nothing
Set WS = Nothing
Set WB = Nothing
Set MyXL = Nothing
Set myDoc = Nothing
MsgBox "Complete"
End Sub
Sub MyInitializeOfficeApps()
On Error Resume Next
Set MyXL = GetObject(, "Excel.Application")
If MyXL Is Nothing Then
Set MyXL = CreateObject("Excel.Application")
End If
On Error GoTo 0
MyXL.Visible = True
End Sub

I am trying to pass values from VB Script back into a mathcad worksheet but the script is failing to create the worksheet object

Can anyone tell me why the activeworksheet object MCWS is not being created by the following VB Script please? It is the code for a combobox in a mathcad worksheet. Thanks
Public Sub SizeBoxEvent_Start()
Dim objEX
Dim objMC
Dim MCWS
Dim objEXWB
Dim objEXWS
Dim intLineNo
Dim objRange
End Sub
Sub SizeBoxEvent_Exec(Inputs,Outputs)
Set objMC = CreateObject("MathCad.Application")
Set MCWS = objMC.ActiveWorkSheet
Set objEX = CreateObject("Excel.Application")
Set objEXWB = GetObject("C:\UB_Dims.xls")
Set objEXWS = objEXWB.worksheets("UB")
Dim MyList(71)
For i = 0 to 71
Mylist(i) = CStr(objEXWS.cells(i+3,1))
'MsgBox Mylist(i)
Next
SizeBox.List() = MyList
intLineNo = SizeBox.ListIndex + 3
objRange = "A" & intLineNo & ":U" & intLineNo
Dim varDimProps(21)
Dim varDimName(21)
For i = 1 to 21
varDimProps(i) = objEXWS.cells(intLineNo,i)
varDimName(i) = CStr(objEXWS.cells(1,i))
Next
MCWS.SetValue "Size", ABC
MCWS.SetValue "M", 288
MCWS.SetValue "D", 203
Outputs(0).Value = varDimProps
End Sub
Sub SizeBoxEvent_Stop()
Rem TODO: Add your code here
End Sub
I haven't used Public subs, so I don't know if your declarations will carry over to other subs. Here's something I picked from the PTC forum that works in Excel 2007 with Mathcad 15.0 (I understand that the excel add in is broken for later excel versions).
My guess is that you should define your objects in the functions that use them. Also, I don't think you can use Activeworksheet for the MathCad worksheet.
Private Function RunMCAD(InputFile As String)
Dim MC As Object
Set MC = CreateObject("Mathcad.Application")
MC.Visible = True
Set Wk = MC.Worksheets
Set WS = Wk.Open("C:\RDDA\RDDA 2014-10-16_excel.xmcd")
WS.SetValue "InputFile", InputFile
WS.Recalculate
WS.Save
WS.Close False
MC.Quit
RunMCAD = "Done"
End Function

Resources