[英]How I can appending data of text file to another text file using VBA MS excel
我有一个Excel宏,该宏在工作表中查找特定的字符串,如果找到该字符串,则将其写入txt文件。
我的问题是txt文件的值被覆盖,但是我想附加到该文件。
我该如何解决?
我的代码是:
Option Explicit
Sub MACRO()
Dim ruta As String
Dim fi As Long
Dim pos As Integer
Dim Sht As Worksheet
Dim cell As Object
fi = FreeFile
ruta = "C:\Users\PE0223\Desktop\Ficheros_Con_Links.txt"
Set Sht = ThisWorkbook.ActiveSheet
On Error GoTo Err
Open ruta For Output As #fi
On Error GoTo 0
'Application.DisplayAlerts = False
For Each cell In Sht.UsedRange.Cells
pos = InStr(cell.Formula, "C:\")
If pos <> 0 Then
Print #fi, ActiveWorkbook.Path & "\" & ThisWorkbook.Name
Exit For
End If
Next
Close #fi
Exit Sub
Err:
Close #fi
End Sub
谢谢!
尝试将行Open ruta For Output As #fi
为
Open ruta For Append As #fi
这应该将数据附加到文本文件,而不是覆盖它。
通过使用“ Find
而不是遍历每个单元格,可以显着改善整体代码。 就像是:
Sub FastDFind()
Dim rng1 As Range
Dim ruta As String
Dim fi As Long
fi = FreeFile
ruta = "C:\Users\PE0223\Desktop\Ficheros_Con_Links.txt"
Open ruta For Append As #fi
Set rng1 = Cells.Find("C:\", , xlFormulas, xlPart)
If Not rng1 Is Nothing Then
MsgBox "value found", vbInformation
Print #fi, ActiveWorkbook.Path & "\" & ThisWorkbook.Name
Close #fi
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.