簡體   English   中英

使用VB將Excel行轉換為文件

[英]Using VB to convert Excel rows to a file

對VB有點缺乏經驗,所以我希望有人可以幫助解決一個簡單的問題!

基本上,我需要為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有一種簡單的方法嗎?

我玩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

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

我從不使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM