Lists in VBscript return object - vbscript

I'm writing a vbscript function that looks something like this:
Public Function fnGetXLSFileCount()
Dim fso, src, folder, file, fileList
Set fileList = CreateObject("System.Collections.ArrayList")
Set fso = CreateObject("Scripting.FileSystemObject")
src = "\\myserver\myfolder"
Set folder = fso.GetFolder(src)
For Each file In folder.files
If LCase(fso.GetExtensionName(file)) = "xlsx" Then
fileList.Add file.name
End If
Next
Set fnGetXLSFileCount = fileList
End Function
As you can see I'm creating an ArrayList and then adding all the names of excel files that exist in a specified folder.
I then call this function and use the Set operator to specify that I'm expecting an object to be returned.
Set XLSFileList = fnGetXLSFileCount
When I check the count on the object it seems to be correct.
When I try to pull the names out there is nothing there. What am I doing incorrectly here?
For each file in XLSFileList
name = file.Item(0)
Next

The For Each loop already enumerates the items of the collection. And since you assign just the names to the collection you simply use the loop variable to get the name:
For Each file In XLSFileList
name = file
Next
The Item property can be used to directly access a specific item from the collection:
WScript.Echo XLSFileList.Item(0)

Related

vb6 Treeview refresh ( show updated file ) in child items

I load treeview1 and treeview2 with same zip names but child items maybe different to each other.
now for the sake of the test i loaded treeview2 with few zip names and it has child items to it, instead of reloading the items i used treeview2.refresh
now leaving the treeview2 items loaded,i open 1 of the zips and add any 1 file in it then going back to treeview2 hit refresh it does not show update unless i reload the items again.
TreeView2.Nodes.Clear
ListFiles app.path & "\folder\", "zip"
ignore the code above i load my items like this ,how do i refresh the items and show updated items without reloading.
Unless you are adding the files to the Zip files through your app, you will have to monitor the content or DateLastModified of the Zip files yourself. You can create a subroutine to iterate through your Zip file names, check their content/DateLastModifed and adjust the nodes in your TreeView. You can call this subroutine on a Timer if the contents of your Zip files changes frequently.
Here's an example of an approach that uses a Dictionary to track each file's LastModifiedDate:
Dim m_objFileModifiedDates As New Dictionary
Dim m_objFSO As New FileSystemObject
Private Sub Command1_Click()
Dim objFolder As Folder
Dim objFile As File
Dim sModifiedFiles As String
Set objFolder = m_objFSO.GetFolder("C:\temp\")
For Each objFile In objFolder.Files
' Check if it exists in Dictionary
If Not m_objFileModifiedDates.Exists(objFile.Name) Then
' Add File
m_objFileModifiedDates.Add objFile.Name, objFile.DateLastModified
Else
' Check Last Modified Date
If m_objFileModifiedDates.Item(objFile.Name) <> objFile.DateLastModified Then
' Update Dictionary
m_objFileModifiedDates.Item(objFile.Name) = objFile.DateLastModified
sModifiedFiles = sModifiedFiles & objFile.Name & vbCrLf
End If
End If
Next
If sModifiedFiles <> "" Then
' Update TreeView with modifed files
MsgBox "Files modified: " & vbCrLf & sModifiedFiles
End If
End Sub
When this detects a file has been modified, you can update your TreeView by reading the modified file's content again and update that TreeView Node, or simply update the whole tree.

HP UFT/QTP 14.00, import CSV and maintain the values in data sheet

i'm importing some data from a csv file, here is the data:
*file.csv
UserName, EmailId, PhoneNumber
Antonio, anto#gmail.com, 1234567890
Oscar, osc#yahoo.com, 9999999999
Luis,lu#hotmail.com,8888888
I have a Function to call this file:
'************************************************************
Function ImportCsvFiletoDatatable(CsvFilePath,SheetName,HeaderDelimiter)
Dim filePath
Dim fso
Dim f
Dim fData
Dim arrData
Dim CsvValue
Dim CsvSheet
Dim CsvFirstLine
Dim CsvColumns
Dim ColumnIndex
Dim rIndex
Dim cIndex
filePath=CsvFilePath 'Specify file Path
'Open CSV File using File System Object
Set fso=createobject("scripting.filesystemobject")
Set f = fso.OpenTextFile(filePath)
CsvFirstLine=f.readline 'Treating like first line is the column names
CsvColumns=split(CsvFirstLine,HeaderDelimiter) 'Split the line using HeaderDelimiter
Set CsvSheet=DataTable.GetSheet(SheetName) 'Get the Specified sheet
'Add the splitted values as Datatable Columns
For ColumnIndex=lbound(CsvColumns) to ubound(CsvColumns)
CsvSheet.addparameter CsvColumns(ColumnIndex),""
Next
While not f.AtEndOfStream
rIndex=f.Line-1 'Specify Row index
fData=f.ReadLine ' Read CSV File Line
arrData=split(fData,",") 'Split the line
cIndex=1 'Specify Column Index
CsvSheet.SetCurrentRow(rIndex) 'Set Row in the Datatable
' Add values in Datatable
For Each CsvValue In arrData
CsvSheet.getparameter(cIndex).value=CsvValue
cIndex=cIndex+1
Next
Wend
f.Close
Set fso=Nothing
End Function
'************************************************************
And works well, but the information is volatile, and i can't manage, or use the data.
Someone know how to keep the data in the data sheet, although leave UFT?
Dim objQtApp, strXlsPath
strXlsPath = Environment("TestDir") & "\Default.xls"
Set objQtApp = CreateObject("QuickTest.Application")
DataTable.Export strXlsPath
objQtApp.Test.DataTable.Import strXlsPath
Set objQtApp = Nothing
The Design Time DataTable is found in the Default.xls. This is loaded when you open a test case or if you edit it manually from UFT. In case you want to refresh it programmatically use the code-snippet above. Export and then with AUtomation Object Import.
Of course put it into a method and call from whatever place is convenient for you.
If you want UFT to take care of it automatically, Create a new Class and a singleton Instance of it.
Implement the Class_Terminate method of the class and put the code there. WHenever UFT exits either because of a crash or or a nomral test run ends, it will try to clean up all Objects created while running. This object will be among them, and as a part of the automatic cleanup process you will save your runtime datatable into the design-time one(Default.xls) and then reload it.

Assign Attachment Field To Variable in Access 2010

I'm trying to understand how to work with the new Attachment field that is available in Access 2010. I would like to assign the value from the table directly into a variable. I know that I can do this if I use an intermediary form, but this seems like sloppy coding to rely on a form in order to grab a value from a table. Is there some way to grab what is in an attachment field and assign it directly to a variable? I have multiple instances where this would be handy for me. The first instance is I want to grab a photo stored in an attachment field to assign to the ribbon. A second instance is to load a company logo from a table into a variable and keep it in memory to use throughout the program as needed.
The code I have so far is this, but it gives me a type mismatch error:
Dim ParentRS As Recordset, ChildRS As Recordset, Img As Attachment
Set ParentRS = CurrentDb.OpenRecordset("SELECT * FROM LtblImg;", dbOpenSnapshot)
If ParentRS.RecordCount > 0 Then
Set ChildRS = ParentRS("Img").Value
If ChildRS.RecordCount > 0 Then
Set Img = ChildRS("FileData")
End If
ChildRS.Close
End If
ParentRS.Close
Yes, Dim Img As Attachment looks tempting, but Attachment (which is actually Access.Attachment) refers to an Attachment control that could be used on a form (just like Access.TextBox) and does not appear to be suitable for your intended purpose.
The only native VBA type for storing this sort of binary data is an array of Byte values, but often when dealing with byte arrays we wind up looping through and processing them byte-by-byte, which is tedious and inefficient.
You might consider using a binary ADODB.Stream object as your "variable". You could create a function to retrieve the attachment bytes and return them in a Stream like so
Option Compare Database
Option Explicit
Public Function GetLogoAsStream() As ADODB.Stream
Dim cdb As DAO.Database, rstMain As DAO.Recordset, rstAttach As DAO.Recordset2, fldAttach As DAO.Field2
' Project references required for early binding:
' Windows Script Host Object Model
' Microsoft ActiveX Data Objects 2.8 Library
Dim fso As FileSystemObject, tempFileSpec As String
Static strm As ADODB.Stream
If strm Is Nothing Then
Set fso = New FileSystemObject
tempFileSpec = fso.GetSpecialFolder(TemporaryFolder) & "\" & fso.GetTempName
Set fso = Nothing
Set cdb = CurrentDb
Set rstMain = cdb.OpenRecordset( _
"SELECT [AttachmentFiles] " & _
"FROM [AttachmentsTable] " & _
"WHERE [Description]='SO logo'", _
dbOpenSnapshot)
Set rstAttach = rstMain("AttachmentFiles").Value
' make sure we use the correct file extension
tempFileSpec = tempFileSpec & "." & rstAttach.Fields("FileType").Value
Set fldAttach = rstAttach.Fields("FileData")
fldAttach.SaveToFile tempFileSpec
Set fldAttach = Nothing
rstAttach.Close
Set rstAttach = Nothing
rstMain.Close
Set rstMain = Nothing
Set cdb = Nothing
Set strm = New ADODB.Stream
strm.Type = adTypeBinary
strm.Open
strm.LoadFromFile tempFileSpec
Kill tempFileSpec
End If
strm.Position = 0
Set GetLogoAsStream = strm
End Function
and then if you had, say, a Report like this with an empty Image control
and an On Load event procedure like this to load the Image control's .PictureData from your "variable" (actually a Function returning an ADODB.Stream)
Private Sub Report_Load()
Me.LogoImage.PictureData = GetLogoAsStream.Read
End Sub
it could produce something like this

How to read and write non-standard document properties of word file in vbscript?

Microsoft Word is offering some default document properties to be set in Word documents.
There is a number of default properties, for which vbscript has constants.
But Word (2011) is offering some more properties, e.g. companyfaxnumber, publishingdate,keywords.
There is a possibility to access the builtin properties by calling
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Documents.Open(strFilePath)
For Each prop In oWord.ActiveDocument.BuiltInDocumentProperties
WScript.Echo prop.Name + "::" + oWord.ActiveDocument.BuiltInDocumentProperties(prop.Name).Value
Next
But how do i find the names of the "custom" properties that are offered by word, but are not present in vbscript as constant?
There is the function
Document.CustomDocumentProperties
But if i do a listing like the one above, i get properties named info1, info2, etc.
Too access the Word CustomDocumentProperties, you will need to be able to access the OLE File Property Reader. This expands beyond the normal/simple document properties because it allows you too add custom properties as well.
There is a Tales from the Script article from 2005 detailing the installation and usage of utilizing CustomDocumentProperties within Word -> Here
For the download to install the OLE Property Reader DLL, Go -> Here
Here is an example of property set/get once the property read is installed:
Const msoPropertyTypeBoolean = 2
Set objFile = CreateObject("DSOFile.OleDocumentProperties")
objFile.Open("C:\Scripts\New_users.xls")
'Set
'=======================================================================
objFile.CustomProperties.Add "Document Reviewed", msoPropertyTypeBoolean
objFile.Save
'Get
'=======================================================================
Set objProperty = objFile.CustomProperties.Item("Document Reviewed")
wscript.echo objProperty.Value
Enjoy!
Hi recently figured out how to get there myself:
The Word "Frontend Editor" is cheating on the document properties. There is a hard defined set of properties like author,category, keywords etc.
The additional properties offered by the editor are so called custom properties which are defined in an external XML structure inside the docx-container.
So there is no easy vbscript function to modify the values of these custom properties.
Thanks to the web, someone did some hacking and this is the solution for it:
Sub WriteCustomCoverProperties(ByRef wordInstance, strProp, strText)
Dim oCustPart
Dim oNode
Dim strXPath
strProp = Replace(strProp, " ", "")
Select Case strProp
Case "Abstract" strXPath = "/ns0:CoverPageProperties[1]/ns0:Abstract[1]"
Case "PublishDate" strXPath = "/ns0:CoverPageProperties[1]/ns0:PublishDate[1]"
Case "CompanyAddress" strXPath = "/ns0:CoverPageProperties[1]/ns0:CompanyAddress[1]"
Case "CompanyPhone" strXPath = "/ns0:CoverPageProperties[1]/ns0:CompanyPhone[1]"
Case "CompanyFax" strXPath = "/ns0:CoverPageProperties[1]/ns0:CompanyFax[1]"
Case "CompanyEmail" strXPath = "/ns0:CoverPageProperties[1]/ns0:CompanyEmail[1]"
Case Else
Exit Sub
End Select
Set oCustPart = wordInstance.ActiveDocument.CustomXMLParts(3)
Set oNode = oCustPart.SelectSingleNode(strXPath)
oNode.Text = strText
Set oCustPart = Nothing
Set oNode = Nothing
End Sub
May it be of help =)

Issue with opening the right path for file dialog

i am using vba access 2010 and have a simple form, a button control. the idea is to create a folder and after which use the filedialog to open up the folder i just created. i am able to create the folder, but how do i open up to the path i just created? below will be the code i have, will really really appreciate it if anyone can help. thanks in advance
Option Compare Database
Private Sub Command0_Click()
Dim Foldername As String
Foldername = "\\server\Instructions\"
MkDir ("C:\Users\Stanley\Desktop\New folder\123")
setProfilePicture
End Sub
'----------------------image path setting---------------------
Private Sub setProfilePicture()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path
'of each selected item. Even though the path is a String,
'the variable must be a Variant because For Each...Next
'routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Change the contents of the Files of Type list.
'Empty the list by clearing the FileDialogFilters collection.
.Filters.Clear
'Add a filter that includes all files.
.Filters.Add "All files", "*.*"
'Add a filter that includes GIF and JPEG images and make it the first item in the list.
.Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1
'Use the Show method to display the File Picker dialog box and return the user's action.
'The user pressed the action button.
If .Show = -1 Then
'Step through each String in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is a String that contains the path of each selected item.
'You can use any file I/O functions that you want to work with this path.
'This example simply displays the path in a message box.
'MsgBox "Path name: " & vrtSelectedItem
Me.ImagePerson.Picture = vrtSelectedItem
'Me.TextboxPersonFilepath.Value = "File path: " & vrtSelectedItem
Next vrtSelectedItem
'The user pressed Cancel.
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
'-----------------end of image path setting--------------
Pass it as a variable.
In your Command0_Click sub, set your directory as a variable, like
X = "MyPath To My Folder"
Then, call setProfilePicture(X)
In setProfilePicture, set it up like:
Private Sub setProfilePicture(MyDir as String)
Then MyDir is now the path to your folder, and you can use it as a variable in your sub

Resources