2012-07-16 65 views
60

我有一個文件,它是根據輸入手動添加或修改的。由於該文件中的大部分內容都是重複的,因此只有十六進制值正在改變,我想讓它成爲工具生成的文件。如何使用VBA創建和寫入到txt文件

我想寫出打算在.txt文件中打印的c代碼。

什麼是創建使用VBA一個.TXT文件中的命令,我怎麼寫它

+0

你想它一旦建立修改現有的文件嗎?當您直接參考腳本運行時,什麼是「c代碼」 – brettdj 2012-07-16 11:34:49

回答

117

使用FSO創建文件和寫入。

Dim fso as Object 
Set fso = CreateObject("Scripting.FileSystemObject") 
Dim oFile as Object 
Set oFile = FSO.CreateTextFile(strPath) 
oFile.WriteLine "test" 
oFile.Close 
Set fso = Nothing 
Set oFile = Nothing  

在這裏看到的文檔:

+12

,您可以使用正確的類型: 'Dim oFs As New FileSystemObject Dim oFile As TextStream' – 2015-06-16 15:10:18

+0

正在使用優於舊通道方法的Scripting Runtime?我希望有一些理由通過其他經驗來支持我的學生。 – 2016-06-07 16:40:17

+0

@RickHenderson,我更喜歡它,如果這就是你的意思。優點是封裝。一旦你反對(設置oFile = Nothing |),或者它超出了範圍,文件將自動關閉。 – Ben 2016-06-08 08:59:17

15

用了很多冗餘的簡單方法。

Dim fso As Object 
    Set fso = CreateObject("Scripting.FileSystemObject") 

    Dim Fileout As Object 
    Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True) 
    Fileout.Write "your string goes here" 
    Fileout.Close 
+0

是否可以使用文件選擇器來設置路徑? – rrs 2017-02-03 17:13:52

-3
Dim SaveVar As Object 

Sub Main() 

    Console.WriteLine("Enter Text") 

    Console.WriteLine("") 

    SaveVar = Console.ReadLine 

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True) 

    Console.WriteLine("") 

    Console.WriteLine("File Saved") 

    Console.WriteLine("") 

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt")) 
    Console.ReadLine() 

End Sub() 
+0

這可以幫助寫作和閱讀文本文件 – 2017-02-10 13:16:51

+1

我認爲你不會讀問題是什麼,也不喜歡解釋你將要嘗試什麼,這在幫助別人時不是一件好事。 – 2017-02-10 13:45:04

+0

而且你甚至沒有正確格式化你的答案。 – BDL 2017-02-10 14:52:08

5
Open ThisWorkbook.Path & "\template.txt" For Output As #1 
Print #1, strContent 
Close #1 
+0

請用一些解釋和細節來寫答案。 – 2017-10-26 20:55:38

+0

這不提供問題的答案。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/17750668) – Rich 2017-10-26 21:21:01

+0

我更喜歡這種方法的FSO方法,因爲它不需要外部引用並且很短。雖然我建議使用FreeFile來獲取文件編號,而不是將其硬編碼爲#1。 – phrebh 2018-02-15 19:52:52