首页 > 解决方案 > 随着代码循环,变量没有更新

问题描述

我编写了一些代码,循环遍历文件夹中的文本文件并使用附加标题“TREATMENT_CODE”更新它们,然后将代码附加到每个文本文件中每一行的末尾。代码取自 txt 文件名。我已经将它设置为一个名为 TCode 的变量。我遇到的问题是 TCode 变量在第一次循环后没有改变。有人可以帮忙吗?谢谢

请原谅所有的 msgbox 行,只是我用它们来弄清楚发生了什么。

代码:

Option Explicit
Dim FSO, FLD, FIL, TS
Dim strFolder, strContent, strPath, FileName, PosA, TCode, rfile, Temp, dataToAppend, fulldata,          wfile, TempArr, i
Const ForReading = 1, ForWriting = 2, ForAppending = 8 

 'Change as needed - this names a folder at the same location as this script
  strFolder = "C:\Users\User1\OneDrive -         Company/Documents\Temporary_delete_every_month\CRM_combiner_macro\Looping_test\files to amend"

 'Create the filesystem object
 Set FSO = CreateObject("Scripting.FileSystemObject")
'Get a reference to the folder you want to search
 set FLD = FSO.GetFolder(strFolder)

'loop through the folder and get the file names
 For Each Fil In FLD.Files
   'MsgBox Fil.Path
 'If UCase(FSO.GetExtensionName(Fil.Name)) = ".txt" Then

strPath = Fil.Path
'msgbox strPath
'strPath = Replace(strPath,"""","")

'msgbox  strPath

 posA = InStrRev(strPath, "\") +1

 TCode = "|"  &  Mid(strPath, posA, 11)

 msgbox "this is TCode " &  TCode

 Set fso = CreateObject("scripting.filesystemobject")

 'msgbox "next file to amend" & strPath

Set rfile = fso.OpenTextFile(strPath, ForReading)                'File opened in Read-only mode

While Not rfile.AtEndOfStream

  temp=rfile.ReadLine()

If rfile.Line=2 Then                             

    dataToAppend = "|TREATMENTCODE"
ElseIf rfile.Line=3 Then
    dataToAppend =  TCode 
End If
fulldata = fulldata & temp & dataToAppend & "|||"
Wend

rfile.Close

fulldata = Left(fulldata,Len(fulldata)-2)

Set wfile = fso.OpenTextFile(strPath, ForWriting)                'File opened in write mode

tempArr = Split(fulldata,"|||")

For i=0 To UBound(tempArr)
wfile.WriteLine tempArr(i)
Next
wfile.Close
Set fso= Nothing

  'End If

'Clean up
Set TS = Nothing
Set FLD = Nothing
Set FSO = Nothing
set rfile = Nothing
set wfile = Nothing
set tempArr = Nothing
set Temp = Nothing
set TCode = Nothing

Next

MsgBox "Done!"

标签: vbscript

解决方案


推荐阅读