2014-04-07 109 views
-1

我在VBA中搜索宏中的一些宏,並在txt文件中寫入excel文件的路徑後,但它不能很好地工作,所有文件中的寫入txt和搜索字符串。我如何做到這一點。如何使用vba編寫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

它似乎不是_vba_代碼。它是_vb.net_? –

+0

「它不能很好地工作」 - 在哪裏工作不好?哪裏不對?哪一行給出錯誤? – Taosique

+0

對不起,我試圖做的vba,但我沒有多少想法的vba,也許我與vb.net –

回答

1

您的代碼似乎是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 
+0

謝謝。是的,我需要這段代碼,並且非常適合比較我的代碼,但是不會在txt文件中寫入任何內容。現在,什麼是錯誤? –

+0

在其中一個單元格中是否有確切的字符串「T:\」?或者,也許它是像「T:\ Subdir \ File.xls」? – Lukas2

+0

在此代碼中,從不輸入每個,我不知道爲什麼 –