我有一个Excel宏,用于在工作表中查找特定字符串,然后在找到此strning时写入 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
谢谢!
答案 0 :(得分:1)
尝试将行Open ruta For Output As #fi
更改为
Open ruta For Append As #fi
这应该将数据附加到文本文件而不是覆盖它。
答案 1 :(得分:0)
您可以使用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