2014-12-02 98 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