2017-02-10 6 views
0

행 1-26의 정보가있는 여러 열 (A-G)이있는 Excel 스프레드 시트가 있습니다. VBA 스크립트를 사용하여 열 A와 D를 열 A와 B로 CSV 파일로 변환하려고합니다. 열 A와 D를 변환 할 수 있었고 A가 올바른 위치에있었습니다 (열 A, 행 1-26) 열 D는 열 D와 행 27-52에서 끝납니다.Excel에서 CSV로만 VBA를 사용하여 특정 열 인쇄

CSV에서 열 B를 Excel의 열 D로 옮기려면 무엇이 누락 되었습니까? 어떤 도움이라도 대단히 감사하겠습니다! 아래의 현재 코드를 참조하십시오.

Dim file As Integer 
Dim filepath As Variant 
Dim filename As Variant 
Dim Row As Integer 
Dim Col As Integer 
Dim Data1 As String 
Dim Data2 As String 
Dim Line As String 
Dim LineValues() As Variant 
Dim OutputFileNum As Integer 
Dim PathName As String 
Dim SheetValues() As Variant 

file = FreeFile 
filepath = "C:\Users\berniea\" 
filename = filepath & "Options" & ".csv" 
Open filename For Output As #file 

SheetValues = Sheets("Features").Range("A1:H26").Value 
Redim LineValues(1 To 8) 

For Row = 2 To 26 
    For Col = 1 To 1 
     LineValues(Col) = SheetValues(Row, Col) 
    Next 
    Data1 = Join(LineValues, ",") 
    Print #file, Data1 
Next 

SheetValues = Sheets("Features").Range("A1:H26").Value 
Redim LineValues(1 To 8) 

For Row = 2 To 26 
    For Col = 4 To 4 
     LineValues(Col) = SheetValues(Row, Col) 
    Next 
    Data2 = Join(LineValues, ",") 
    Print #file, Data2 
Next 

Close #file 

End Sub 

답변

0

나는 더 간단하다 생각 :

Dim text As String 
file = FreeFile 
filepath = "C:\Users\berniea\" 
filename = filepath & "Options" & ".csv" 
Open filename For Output As #file 
For Row = 2 To 26 
text = text + Cells(Row, 1) & "," & Cells(Row, 4) & vbNewLine 
Next Row 
Print #file, text 
Close #file 
+0

완벽하게 작동합니다! 정말 고마워! : D – Angela

+0

언제든지 환영합니다.) –

1

나는 가능한 한 코드를 단순화했습니다.

Sub ColsAD() 
    Dim file As Integer: file = FreeFile 
    Open "C:\Users\berniea\Options.csv" For Output As #file 

    Dim row As Long, line As String 
    For row = 2 To 26 
     With Sheets("Features") 
      line = .Cells(row, 1) & "," & .Cells(row, 4) 
     End With 
     Print #file, line 
    Next 
    Close #file 
End Sub