Open "A.txt" For Output As #1 - How to make Output a Sub argument?

  • Thread starter gimme_this_gimme_that
  • Start date
G

gimme_this_gimme_that

Consider the following code:

Sub WriteHello()
Open "A.txt" For Output As #1
Print #1 "hello world"
Close #1
End Sub

How can this WriteHello Sub be modified so that the file descriptor is
an argument to a separtee Sub? Something like:


Sub WriteHello()
Open "emmett_output.txt" For Output As #1
PrintLine #1 ,"hello world"
Close #1
End Sub

Sub Println(f as variant, str as String)
Print f,str
End Sub

Eventually I want to write several Worksheets to a single TXT file.

"f" isn't a variant. What is it?

Thanks.
 
C

Chip Pearson

Try something like


Sub HelloWorld(FileName As String)
Open FileName For Output As #1
Print #1, "hello world"
Close #1
End Sub

You can then pass the file name from another procedure with code like:

Sub Test()
Dim FName As String
FName = "C:\Path\File.txt"
HelloWorld FileName:=FName
End Sub


--
Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group, 1998 - 2008
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)
 
G

gimme_this_gimme_that

Thanks Chip,

But you missed the idea behind the post.

I don't want to have an Open,Print, and Close statement in every sub
that writes to that file.

You just copied my original HelloWorld sub and declare that the
solution.
 
C

Chip Pearson

Your post was less than clear. If you mean how do you pass the file number
(e.g. the "#1"), it is an integer that can be passed around as any normal
variable.


Private pFile1 As Integer
Private pFile2 As Integer

Sub AAA()
Dim N As Long
pFile1 = FreeFile()
Open "C:\Test\T1.txt" For Output As #pFile1
pFile2 = FreeFile()
Open "C:\Test\T2.txt" For Output As #pFile2
For N = 1 To 10
If N Mod 2 = 1 Then
PrintIt pFile1, "Odd N = " & CStr(N)
Else
PrintIt pFile2, "Even N = " & CStr(N)
End If
Next N
Close #pFile1
Close #pFile2
End Sub


Sub PrintIt(FileNum As Integer, S As String)
Print #FileNum, S
End Sub



--
Cordially,
Chip Pearson
Microsoft Most Valuable Professional
Excel Product Group, 1998 - 2008
Pearson Software Consulting, LLC
www.cpearson.com
(email on web site)



Thanks Chip,

But you missed the idea behind the post.

I don't want to have an Open,Print, and Close statement in every sub
that writes to that file.

You just copied my original HelloWorld sub and declare that the
solution.
 
G

gimme_this_gimme_that

Your post was less than clear.  If you mean how do you pass the file number
(e.g. the "#1"), it is an integer that can be passed around as any normal
variable.

Ooooooh. Thanks Chip! That's exactly what I needed. My bad about the
clarity.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top