2015-08-18 117 views
0

我在努力弄清楚如何連接這兩段代碼,我找到了一起。將列保存爲文本循環帶文件名循環

我有一張c.400列的表格,我想將每列保存爲一個.txt文件。問題在於我需要使用另一個工作表上指定的名稱來保存文件(全部按照列的順序)。

我認爲兩塊VBA相關的是:

Sub VBA_write_to_a_text_file_from_Excel_Range() 
    Dim iCntr as Lonng 
    Dim strFile_Path As String 
    strFile_Path = "C:\temp\test.txt" 

    Open strFile_Path For Output As #1 
For iCntr = 1 To 10 
    Write #1, Range("A" & iCntr) 
Next iCntr 
    Close #1 
End Sub 

Sub CreateFolder() 
Dim MyFile As String 
MyFile = Sheets("Request form").Range("F9").Text 
ActiveWorkbook.SaveAs Filename:=sDir & "\" & MyFile 
End Sub 

任何幫助將不勝感激。

謝謝

克里斯

+0

嘿@CDH,歡迎SO!你更具體地經歷了什麼錯誤?什麼是'catch'? – Klaster

+0

不清楚?像這樣說... 1.你需要什麼...... 2.你的代碼是什麼...... 3.代碼的問題是什麼......!這樣發佈。 –

+0

嗨@Klaster,我有一張c.400列的表格,我想將每列保存爲一個.txt文件。問題在於我需要使用另一個工作表上指定的名稱來保存文件(全部按照列的順序)。它需要兩個循環 - 一個保存列和一個尋找名稱。我認爲。道歉,我對VBA很陌生。 – CDH

回答

0

這裏有2種方式,以節省列到文本文件:

Option Explicit 

Private fso As Variant 

Sub saveColsToText() 
    Const START_COL As Long = 2 
    Const START_ROW As Long = 2 
    Const FNAME_ROW As Long = 2 
    Const F_PATH As String = "C:\Temp\" 

    Dim ws1 As Worksheet, ws2 As Worksheet, thisCol As Range 
    Dim lr As Long, lc As Long, i As Long, colStr As String 

    Set fso = CreateObject("Scripting.FileSystemObject") 

    Set ws1 = Worksheets("Sheet1") 
    Set ws2 = Worksheets("Sheet2") 

    With ws1 
     lc = .Cells(1, .Columns.Count).End(xlToLeft).Column 
     lr = .Cells(.Rows.Count, 1).End(xlUp).Row 

     For i = START_COL To lc 
      Set thisCol = .Range(.Cells(1, i), .Cells(lr, i)) 
      colStr = Join(Application.Transpose(thisCol.Value2), vbCrLf) 
      saveColToFile1 F_PATH, ws2.Cells(FNAME_ROW, i).Value2 & ".txt", colStr 
     Next 
    End With 
End Sub 

Sub saveColToFile1(ByVal fPath As String, ByVal fName As String, ByVal colText As String) 
    Dim fileID As Variant 

    If Len(Dir(fPath)) = 0 Then MkDir fPath 
    Set fileID = fso.CreateTextFile(fPath & fName, True) 
    fileID.Write colText 
    fileID.Close 
    Set fileID = Nothing 
End Sub 

Sub saveColToFile2(ByVal fPath As String, ByVal fName As String, ByVal colText As String) 
    Open fPath & fName For Output As #1 
    Write #1, colText 
    Close #1 
End Sub 

'------------------------------------------------------------------------------------------