打开文本文件,从文件中获取数字/文本,并将文本/数字增加1

时间:2014-12-02 15:53:01

标签: vba text-files

我有一个.txt文件,Supplier Count.txt,在我的Excel电子表格中,每次运行VBA代码时我都要打开这个文件,以读取我的文本文件中的数字值,例如: ' 21'然后将其递增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 个答案:

答案 0 :(得分: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