I have three functions, in macros excel. i am showing an example to understand
Sub main()
Dim Obj As Object
Dim File As Object
Set Obj = CreateObject("Scripting.FileSystemObject")
Set File = Obj.createtextfile("c:\amix.txt"", True)
A
B
C
End sub
Public Function A()
file.writeline("ABC")
End Function
Public Function B()
file.writeline("Def")
End Function
Public Function C()
file.writeline("GHI")
End Function
Now i want to write all this function data into amix.txt notepad
And also if we write the two(Creating the Obj and Files) lines in every function, the text file is over riding for every function.
Now can you please suggest me with the code where i can get rid of my problem?
Obviously, the error is you are not passing File
to your functions. Try the following. It's tried and tested to work. Also, your directory has an extra "
at the end. Not sure if just a typo on your part.
Sub main()
Dim Obj As Object
Dim File As Object
Set Obj = CreateObject("Scripting.FileSystemObject")
Set File = Obj.CreateTextFile("c:\amix.txt", True)
WriteA File
WriteB File
WriteC File
End Sub
Public Function WriteA(File As Object)
File.writeline "ABC"
End Function
Public Function WriteB(File As Object)
File.writeline "DEF"
End Function
Public Function WriteC(File As Object)
File.writeline "GHI"
End Function
Hope this helps.
EDIT:
If you want to call a function inside another, just make sure the inner function exists first. There are no issues doing this. However, the practice is generally unorthodox at best. Same follows (tested and working):
Public Function WriteC(File As Object)
'Calling WriteB inside WriteC as well.
File.writeline "GHI"
WriteB File
End Function
Let us know if this helps.
You need to make your text file object Global. You also should use Subs rather than Functions . For example:
Dim Obj As Object
Dim Ffile As Object
Sub main()
Set Obj = CreateObject("Scripting.FileSystemObject")
Set Ffile = Obj.createtextfile("C:\TestFolder\amix.txt", True)
Call A
Call B
Call C
End Sub
Sub A()
Ffile.writeline ("ABC")
End Sub
Sub B()
Ffile.writeline ("Def")
End Sub
Sub C()
Ffile.writeline ("GHI")
End Sub
Also, eventually you should perform
Ffile.Close
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.