2014-12-02 40 views
0

我有一個.txt文件,供應商Count.txt,並在我的Excel電子表格中,每次運行VBA代碼時,我都希望此文件是打開,閱讀我的文本文件中的數字值,例如'21'然後遞增1.打開文本文件,從文件中獲取數字/文本並將文本/數字增加1

所以說我們的文本文件有一行文本,這行文本是一個數字'21'。 vba代碼應打開該文件,讀取該數字並將其加1並替換文本,保存並關閉文本文件。所以我們的價值是'22'

沒有人知道我可以做到這一點,因爲我是全新的vba,迄今爲止所有能夠想出的是打開文本文件並將數字讀出一個MsgBox

Application.ScreenUpdating = False 
On Error GoTo ErrHandler12: 
Dim FilePath12 As String 
Dim Total12 As String 
Dim strLine12 As String 
FilePath12 = "\\ServerFilePath\assets\Supplier Count.txt" 
Open FilePath12 For Input As #1 

While EOF(1) = False 
    'read the next line of data in the text file 
    Line Input #1, strLine12 
    Total12 = Total12 & vbNewLine & strLine12 
    'increment the row counter 
    i = i + 1 
Wend 
Close #1 
MsgBox Total12 
ErrHandler12: 

Application.ScreenUpdating = True 
+1

「記事本文件」?沒有這樣的事情,真的。你有一個「.txt」文件,它很可能在記事本中打開。 – 2014-12-02 15:58:22

+0

這個文本文件只有一個數字嗎?它會有不止一行嗎? – 2014-12-02 16:02:42

+0

它將是一個數字,但可能有多個小數或可能是一個或兩個數字的數字等,但只有一個數字值是,並且只會是一行 – 2014-12-02 16:05:26

回答

0

首先包括對FileSystemObject參考(見https://stackoverflow.com/a/5798392/380384

然後運行這個

Private fso As New FileSystemObject 

Public Sub IncrCount() 
    Dim path As String 
    path = fso.BuildPath("\\server\share\folder", "SupplierCount.txt") 
    Dim fs As TextStream 
    Set fs = fso.OpenTextFile(path, ForReading) 
    Dim counter As Long 
    counter = CInt(fs.ReadLine()) 
    fs.Close 

    Set fs = fso.OpenTextFile(path, ForWriting, True) 
    fs.WriteLine CStr(counter + 1) 
    fs.Close 
End Sub 
+0

感謝您的建議,但這會導致用戶定義的對象未定義的錯誤。我不認爲它喜歡Dim fs As TextStream line – 2014-12-02 16:10:32

+0

您可以包含對Microsoft Scripting Runtime的引用(請參閱後面的鏈接)以訪問「TextStream」和「FileSystemObject」。 – ja72 2014-12-02 16:12:42