Assign Attachment Field To Variable in Access 2010 - image

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

Related

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.

Run-time error '91' when adding data to a record set

I want to insert some information into a database in VB6, but I get runtime error '91'.
My code:
Private sub btn_click()
Fname = txtFname.text
Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("Fname") = Fname
Adodc1.Recordset.Update
End sub
The debuger shows error on: Adodc.Recordset.AddNew
You haven't posted the rest of the code as to where the Adhoc1 variable is created etc...
This post suggests that the RecordSet has not been initialized prior to working with it, but it's hard to be more specific without the code.
Runtime error '91' is Object variable or With block variable not set, which is a slightly confusing way to say that your variable contains Nothing.
You either forgot to initialise the Adodc1 properly, or, and this is more likely, you need to initialise Adodc1.RecordSet to something useful (like a Set Adodc1.RecordSet = New RecordSet or related) before you can use it.
By the way you posted the code, I believe that you will populate a Recordset to insert into the database. Try as follows:
sub btn_click()
dim Adodc1 as adodb.recordset
set Adodc1 = new adodb.recordset
Fname = txtFname.text
Rs.Fields.Append "Fname", adVarChar, 20 'adVarChar = text, followed by the amount of characters
Adodc1.open()
Adodc1.Recordset.AddNew
Adodc1.Recordset.Fields("Fname") = Fname
Adodc1.Recordset.Update
End sub

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 =)

Export data from listview to OpenOffice VB6

I have a program that displays data from a CSV file into a ListView.
I then have a button called "Reports" - when I click this I want the data to be displayed from the ListView/CSV file in OpenOffice Calc.
This is my code:
Private Sub cmdReports_Click()
Dim oSM As Object
Dim oDesk As Object
Dim oDoc As Object
Dim oSheet As Object
Dim i As Integer
'Instanciate OOo : this line is mandatory with VB for OOo API
Set oSM = CreateObject("com.sun.star.ServiceManage…
'Create the first and most important service
Set oDesk = oSM.CreateInstance("com.sun.star.frame.D…
'Create a new doc
Set oDoc = oDesk.loadComponentFromURL("private:fact… "_blank", _
0, arg())
'Get the first sheet in the doc
Set oSheet = oDoc.getSheets().getByIndex(0)
With oSheet
For i = 1 To ListView1.ListItems.Count
.cells(i, 1) = ListView1.ListItems(i).Text
.cells(i, 2) = ListView1.ListItems(i).SubItems(1)
.cells(i, 3) = ListView1.ListItems(i).SubItems(2)
.cells(i, 4) = ListView1.ListItems(i).SubItems(3)
Next
End With
End Sub
At the moment all my button is doing giving me Run-time error '438' Object does not support this property or method
When I debug this line is highlighted:
.cells(i, 1) = ListView1.ListItems(i).Text
This code was written for Excel but I edited it so it can be displayed in OpenOffice Calc.
Can anyone help please?
Thanks
It means exactly what it says - the statement is using a property of method that isn't supported by the Ole Automation interface. First question: can you use a type library (see the References dialogue - is there something like OpenOffice Calc in the list)? Knowing what methods and properties are available at compile time is much better - you can do the same with Microsoft Excel. Then you could declare your variables as a specific type, rather than "As Object".
Not knowing OpenOffice, I looked for documentation on OpenOffice, and found the next best thing, Star Office. Try: http://www.openoffice.org/api/basic/man/tutorial/tutorial.pdf . Look at page 64, section 4.4 for documentation on the spreadsheets. The object model looks different to Office, which would explain your problem.
It looks as if you need to use the Sheet.getCellByPosition() method, rather than the Cells() method, e.g.
GetCell = oSheet.getCellByPosition (nColumn , nRow)

List audio input devices - VBA

I have a bit of a complex Access Database that I need to do some audio recording with. I have nearly everything working using outside solutions but I am forced to select my input device from within Access.
All that I need is some way to get a collection of devices or something from Windows and I can take it from there. http://www.vbmonster.com/Uwe/Forum.aspx/vb/32848/listing-all-audio-devices does something close to what I am looking for except that is the output instead of the input. I know that there will be no extremely easy way to accomplish this but I know it is possible, I just can't seem to find how.
The code you linked creates a SWbemObjectSet, then lists properties of its members (sound devices). From what I can tell, you want that object but don't want to list the properties ("output").
If that is correct, create a function which strips away the output statements and just returns the SWbemObjectSet object.
Public Function getSoundDevices(Optional strComputer As String = ".") As Object
Const cstrQuery As String = "Select * from Win32_SoundDevice"
Dim objWMIService As Object 'TypeName = SWbemServicesEx '
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set getSoundDevices = objWMIService.ExecQuery(cstrQuery, , 48)
Set objWMIService = Nothing
End Function
Then call the function to use the SWbemObjectSet as input for your other code.
Public Sub test_getSoundDevices()
Dim objSoundDevices As Object 'TypeName = SWbemObjectSet '
Dim objDevice As Object 'TypeName = SWbemObjectEx '
Set objSoundDevices = getSoundDevices()
For Each objDevice In objSoundDevices
'* do what you want for each sound device here *'
Debug.Print "ProductName: " & objDevice.ProductName
Next objDevice
Set objDevice = Nothing
Set objSoundDevices = Nothing
End Sub
Hmm, not the easiest question :-) I think you indeed need to invoke a native function.
Maby something like this:
http://msdn.microsoft.com/en-us/library/ms645598(v=vs.85).aspx
VB implementation in the bottom.
Good luck!

Resources