仅使用VBA将Excel转换为CSV打印特定列 [英] Excel to CSV print specific columns only using VBA

查看:102
本文介绍了仅使用VBA将Excel转换为CSV打印特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Excel电子表格,该电子表格具有多列(A-G),并在第1-26行中包含信息.我正在尝试使用VBA脚本将仅A列和D列转换为CSV文件并转换为A列和B列.我已经能够将A列和D列转换为A位置正确(A列,第1-26行),但D列最终排在D列和第27-52行.

I have an Excel spreadsheet that has multiple columns (A-G) with information in rows 1-26. I am trying to use a VBA script to convert only columns A and D to the CSV file to columns A and B. I have been able to convert columns A and D and A is in the correct position (column A, rows 1-26), but column D ends up in column D and rows 27-52.

将excel中的D列移到CSV中的B列时我缺少什么?任何帮助将不胜感激!请参阅下面的当前代码:

What am I missing to move column D in excel to column B in the CSV? Any help would be greatly appreciated! See my current code below:

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

推荐答案

我认为它更简单:

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

这篇关于仅使用VBA将Excel转换为CSV打印特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆