如何用vba写入txt文件

时间:2014-04-07 08:26:34

标签: excel vba

我在VBA中有一个宏在单元格中搜索一些字符串,并在txt文件中写入excel文件的路径,但它不能很好地工作,写入文件txt和搜索字符串。我怎么能这样做。

谢谢!

我的代码是:

属性VB_Name =“Buscar_String”

Sub MACRO()
    Dim ruta As String = "C:\Ficheros_Con_Links.txt"
    Dim fi As FileInfo = New FileInfo(ruta)
    Dim sw As StreamWriter
    Dim Sht As Worksheet
    Application.DisplayAlerts = False
    For Each cell in Sht.Cells 
        If strComp(cell, "T:\", 1) = 0 then
            If File.Exists(ruta) = False Then
                sw = File.CreateText(ruta)
            End If
        sw.WriteLine (ActiveWorkbook.Path & "\" & ThisWorkbook.Name)
        sw.Flush()
        sw.Close()
        End If
    Next
End Sub

现在,我改变了我的代码,并且运作良好

   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
        End If
    Next

    Close #fi
    Exit Sub

Err:
    Close #fi
End Sub

1 个答案:

答案 0 :(得分:2)

您的代码似乎是vb.net,而不是vba。

如果你需要在vba中的解决方案,这里是代码:

Option Explicit

Sub MACRO()
    Dim ruta As String
    Dim fi As Long
    Dim Sht As Worksheet
    Dim cell As Object

    fi = FreeFile
    ruta = "D:\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
        If StrComp(cell, "T:\", 1) = 0 Then
            Print #fi, ActiveWorkbook.Path & "\" & ThisWorkbook.Name
        End If
    Next

    Close #fi
    Exit Sub

Err:
    Close #fi
End Sub

更新:

正如评论中所讨论的,请参阅下面更改的代码 - 即使文本的字符串较长,也应该找到文本。

Sub MACRO()
    Dim ruta As String
    Dim fi As Long
    Dim Sht As Worksheet
    Dim cell As Range

    fi = FreeFile
    ruta = "D:\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
         If InStr(cell.Value, "T:\") > 0 Then
            Print #fi, ActiveWorkbook.Path & "\" & ThisWorkbook.Name
        End If
    Next

    Close #fi
    Exit Sub

Err:
    Close #fi
End Sub