2013-02-25 1 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를 할 수있는 간단한 방법이 있나요? 내가 VBA 함께 연주하지만,이 같은 일을해야하기 때문에

+0

당신이 독점 이럴있는 태그'vb.net'와'script' 있습니다. 이것은 VB.NET 프로그램입니까, 아니면 VBA 스크립트입니까? – GolfWolf

+0

@ w0lf Windows Script File이 이상적입니다. –

답변

1

그것은 잠시되었습니다 : -

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 테스트 파일에 오류가 발생합니다 (예제와 동일하게 형식화 됨). –

+0

편집을보고 도구 -> 참조 -> Microsoft Scripting Runtime으로 이동하여 Microsoft Scripting Runtime을 참조하십시오. – chrisw

+0

이것은 첫 번째 행이 1 행에서 시작하는 것으로 가정합니다. 데이터는 행 5에서 시작하여 iLoop의 초기 값을 5로 변경합니다. – chrisw

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 
관련 문제