简体   繁体   English

需要从函数中检索数据并在宏Excel中写入文本文件

[英]Need to retrieve the data from the function and write in the text file in macros excel

I have three functions, in macros excel. 我在宏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 现在我想将所有这些功能数据写入amix.txt记事本

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. 显然,错误是您没有将File传递给函数。 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. 您需要将文本文件对象设置为Global。 You also should use Subs rather than Functions . 您还应该使用Subs而不是Function 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM