2013-02-25 53 views
0

對VB有點不熟悉,所以我希望有人能夠幫助解決一個簡單的問題!使用VB將Excel行轉換爲文件

基本上,我需要爲Excel電子表格的每一行生成一個文本文件(帶.exp擴展名)。但是,列數和行數是事先未知的,格式需要相當具體。例如,給定以下Excel格式:

 
Col1 | Col2 
1 | 2 
8 | 9 
17 | 46 

我期望生成3個文件。第一個文件內容如下:

Col1 1 
Col2 2 

第二:

 
Col1 8 
Col2 9 

第三:

 
Col1 17 
Col2 46 

有一個簡單的方法來做到這一點使用VB?

+0

你必須標記'vb.net'和'script'這是獨家恕我直言。這是一個VB.NET程序還是VBA腳本? – GolfWolf 2013-02-25 09:54:12

+0

@ w0lf理想情況下,它應該是Windows腳本文件。 – 2013-02-25 10:15:41

回答

1

這已經有一段時間,因爲我打了VBA,但這樣的事情應該工作: -

Dim fso As New FileSystemObject 
Dim stream As TextStream 
Dim iLoop As Integer 
iLoop = 1 
While Sheets("Sheet1").Range("A" & iLoop) <> "" 
    Set stream = fso.CreateTextFile("C:\Row" & iLoop & ".txt", True) 
    stream.WriteLine "Col1 " & Sheets("Sheet1").Range("A" & iLoop) 
    stream.WriteLine "Col2 " & Sheets("Sheet1").Range("B" & iLoop) 
    stream.Close 
    iLoop = iLoop + 1 
Wend 

可能需要一些調整,我沒有測試過這一點,但,這是基本的想法。

+0

看起來很有前途,但在第6行中輸入了錯誤,字符10與我的Excel測試文件(格式與我的示例相同)。 – 2013-02-25 10:14:24

+0

請參閱編輯,並確保通過轉到工具 - >參考 - >'Microsoft腳本運行時'參考Microsoft腳本運行時 – chrisw 2013-02-25 10:52:25

+0

這是一個示例,當然,它假定您的第一行從第1行開始。如果您的數據從第5行開始,然後將iLoop的初始值更改爲5 – chrisw 2013-02-25 10:55:06

1

我從來沒有使用Excel,也沒有一個副本來測試任何代碼,所以請耐心等待。

的基想法的VBScript(單機.vbs文件)...

'connect to Excel 
Set XLApp = CreateObject("Excel.Application") 
XLApp.Visible = True 

'open the file 
XLApp.DisplayAlerts = False 
Set XLBook = XLApp.WorkBooks.Open("c:\path_to\my.xls") 
XLApp.DisplayAlerts = True 

'if you know the Worksheet name: 
sSheetName = "MySheetName" 
Set XLSheet = XLBook.Sheets.Item(sSheetName) 

'else use index: 
Set XLSheet = XLBook.Worksheets(1) 

'or if you want to process all sheets: 
For Iter = 1 To XLBook.Worksheets.Count 
    Set XLSheet = XLBook.Worksheets(Iter) 
    ... 
Next 

'you can use XLSheet.Columns.Count to iterate 
'or if the columns names are known: 
Set Col1 = XLSheet.Columns("Col1") 
Set Col2 = XLSheet.Columns("Col2") 

'or get Range: 
Set Range = XLSheet.Columns("Col1:Col2") 
'same as above: 
Set Range = XLSheet.Range("Col1:Col2") 

'vbs FileSystemObject: 
Set fso = CreateObject("Scripting.FileSystemObject") 

iLoop = 1 'to enumerate file names 
intRow = 2 '?... not sure about this 

Do While Range.Cells(intRow,1).Value <> "" 
    Set stream = fso.CreateTextFile("Row" & iLoop & ".exp", True) 
     stream.WriteLine "Col1 " & Range.Cells(intRow, 1).Value 
     stream.WriteLine "Col2 " & Range.Cells(intRow, 2).Value 
    stream.Close 
    iLoop = iLoop + 1 
    intRow = intRow + 1 
Loop 

'XLBook.Save 
XLBook.Close 
XLApp.Quit 

Set stream = Nothing 
Set fso = Nothing 
Set Range = Nothing 
Set XLSheet = Nothing 
Set XLBook = Nothing 
Set XLApp = Nothing