【问题标题】:Open text file, get number/text from file and increment text/number by 1打开文本文件,从文件中获取数字/文本并将文本/数字增加 1
【发布时间】:2014-12-02 15:53:00
【问题描述】:

我有一个 .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

【问题讨论】:

  • “记事本文件”?没有这样的事,真的。您有一个“.txt”文件,很可能会在记事本中打开。
  • 这个文本文件是不是只有一个数字?它会有多于一条线吗?
  • 它将是一个数字,但可能有多个小数,或者可能是一位数或两位数等,但只有一个数字值是的,并且永远是一行

标签: vba text-files


【解决方案1】:

首先包含对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

【讨论】:

  • 感谢您的建议,但这会导致用户定义的对象未定义错误。我不认为它喜欢 Dim fs As TextStream 行
  • 必须包含对 Microsoft Scripting Runtime 的引用(请参阅帖子中的链接)以访问 TextStreamFileSystemObject
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多