0

VB に少し慣れていないので、誰かが簡単な問題のように感じるものを助けてくれることを願っています!

基本的に、Excel スプレッドシートの行ごとにテキスト ファイル (拡張子は .exp) を生成する必要があります。ただし、列と行の数は事前に不明であり、形式はかなり具体的である必要があります。たとえば、次の Excel 形式があるとします。

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

3 つのファイルが作成されると予想されます。最初のファイルは次のようになります。

列1 1
コル2 2

二番目:

列1 8
コル2 9

第3:

Col1 17
コル2 46

VB を使用してこれを行う簡単な方法はありますか?

4

2 に答える 2

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
于 2013-02-25T11:51:54.733 に答える
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

微調整が必​​要な場合があります。これはテストしていませんが、これが基本的な考え方です。

于 2013-02-25T09:56:50.797 に答える