View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
deltaquattro deltaquattro is offline
external usenet poster
 
Posts: 65
Default Cannot write the contents of an Object to file

Hi,

I would like to write the contents of a Collection of Objects to a
file, but I'm having a lot of problems. Can you help me? Here's a
simplified version of my code, which reproduces the problem:

----------------
Main----------------------------------------------------------
Sub test()
Dim I As Long, Record As CRecord, Coll As Collection

Set Record = New CRecord
Set Coll = New Collection

For I = 1 To 26
Record.Linea(I) = "foobar" & I
Next I

Coll.Add Item:=Record

Call WriteDataToFile("foo.txt", Coll)

End Sub
--------------------------------------------------------------------------------------

The CRecord Class Module follows:

----CRecord
Class-------------------------------------------------------------
Option Explicit

Private pLinea(1 To 26) As String

' Left Limit Property
Public Property Get Linea(Index As Long) As String
Linea = pLinea(Index)
End Property
Public Property Let Linea(Index As Long, Value As String)
pLinea(Index) = Value
End Property

' PrintToFile Method
Public Function PrintToFile(FileUnit As Integer)
Dim I As Long
For I = 1 To NLines
Print #FileUnit, Linea(I)
Next I
End Function
----------------------------------------------------------------------------------------

Finally, here's the WriteDataToFile function:


-----------------------
WriteDataToFile--------------------------------------------------------------------------------------
Function WriteDataToFile(FileName As String, Container As Variant) As
Boolean
'Write each element contained in Container (either an array or a
collection) to file FileName
Dim FNumber As Integer, Element As Variant

'Find free file number
FNumber = FreeFile

'Create new file or overwrite existing one
Open FileName For Output As #FNumber

'Write array to file
For Each Element In Container
If IsObject(Element) Then
Element.PrintToFile FileUnit:=FNumber
Else
Print #FNumber, Element
End If
Next

'Close file and exit
Close #FNumber

End Function
---------------------------------------------------------------------------------


The error I get when running test() is
"Run-time error 52:

Bad file name or number"

However, the file name is an allowed one ("foo.txt") and the file
number is surely ok, since I get it using the intrinsic VB function
FreeFile, which returns an Integer corresponding to a free file
number. So I really don't know what's happening here. Can you help me?
Thanks,

Best Regards

deltaquattro