Open text file, get number/text from file and increment text/number by 1

大憨熊 提交于 2019-12-12 02:26:56

问题


I have a .txt file, Supplier Count.txt and in my excel spreadsheet, each time I run a VBA code I want this file to be opened, to read the number value in my text file, e.g. '21' and then increment it by 1.

So say our text file has one line of text, and this line of text is a number, '21'. the vba code should open the file, read this number and increment it by 1 and replace the text, save it and close the text file. so our value is then '22'

does anyone know how I can do this as I am completely new to vba and so far all ive been able to come up with is the opening the text file and reading the number out as a 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:


First include a reference to the FileSystemObject (see https://stackoverflow.com/a/5798392/380384)

Then run this

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


来源:https://stackoverflow.com/questions/27253550/open-text-file-get-number-text-from-file-and-increment-text-number-by-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!