2013-12-11 66 views
0

我收到一個有n列數量的excel文件,我必須製作一個宏來只複製A到C列,而行數是未知的。此外,我必須將數據以連續形式導出到ascii文件,而不是表格。我發現下面的代碼在http://www.mcgimpsey.com/excel/textfiles.html如何使用宏以非表格形式將excel複製到ascii文件?

Public Sub CharacterSV() 
    Const DELIMITER As String = "|" 
    Dim myRecord As Range 
    Dim myField As Range 
    Dim nFileNum As Long 
    Dim sOut As String 

    nFileNum = FreeFile 
    Open "Test.txt" For Output As #nFileNum 
    For Each myRecord In Range("A1:A" & _ 
       Range("A" & Rows.Count).End(xlUp).Row) 
     With myRecord 
      For Each myField In Range(.Cells, _ 
        Cells(.Row, Columns.Count).End(xlToLeft)) 
       sOut = sOut & DELIMITER & myField.Text 
      Next myField 
      Print #nFileNum, Mid(sOut, 2) 
      sOut = Empty 
     End With 
    Next myRecord 
    Close #nFileNum 
End Sub 

然而,這是給我的輸出以表格形式。我的經驗是在C#中,我在excel中很少有經驗,在VBA和宏中是全新的,所以如果你能對此有所幫助,我將非常感激。

編輯:

輸入包括A列名B列姓氏和C列的ID號,看起來像這樣:

John Smith 12345656 
James Doe  94848484 
Jill Miles 78475899 
Frank Young 48758599 

輸出應該是這個樣子:

John Smith 12345656 James Doe 94848484 Jill Miles 78475899 Frank Young 48758599

+1

你是什麼意思,「連續的形式,而不是表格」?請給我們一個例子。 –

+0

向我們展示輸入的外觀以及相應輸出的外觀。 –

+0

我編輯了包括輸入和輸出示例的問題。 –

回答

1

這(不言自明)應該爲你工作。您可能想要使用不同的代碼來定義源範圍。

Sub cont_out() 
    Dim rng1 As Range, cl As Range 
    Set rng1 = Range("A1") 
    Set rng1 = Range(rng1, rng1.End(xlDown).End(xlToRight)) 

    Dim strPath As String 
    strPath = "test.txt" 
    Dim fnum As Integer 
    fnum = FreeFile() 
    Open strPath For Output As #fnum 

    For Each cl In rng1 
     Print #fnum, cl.Text & " "; 
    Next cl 

    Close #fnum 
End Sub 
+0

完美滿足我的需求!非常感謝你! –

相關問題