打开文本文件,从文件中获取数字/文本并将文本/数字增加 1 [英] Open text file, get number/text from file and increment text/number by 1

查看:63
本文介绍了打开文本文件,从文件中获取数字/文本并将文本/数字增加 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .txt 文件,Supplier Count.txt,在我的 excel 电子表格中,每次运行 VBA 代码时,我都希望打开此文件,以读取文本文件中的数值,例如'21' 然后加 1.

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.

假设我们的文本文件有一行文本,而这行文本是一个数字,21".vba 代码应该打开文件,读取这个数字并将其增加 1 并替换文本,保存并关闭文本文件.所以我们的值是'22'

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'

有谁知道我如何做到这一点,因为我是 vba 的新手,到目前为止我能想到的就是打开文本文件并将数字作为 msgbox 读出

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

推荐答案

首先包含对 FileSystemObject 的引用(参见 https://stackoverflow.com/a/5798392/380384)

First include a reference to the FileSystemObject (see 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

这篇关于打开文本文件,从文件中获取数字/文本并将文本/数字增加 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆