vba 列转行 逗号分隔 写成csv文件
时间: 2024-01-31 10:46:02 浏览: 132
VBA_读写文件
以下是将列转行,并将结果逗号分隔写入CSV文件的VBA代码:
```vb
Sub ColumnToRow()
Dim inputRange As Range
Dim outputRange As Range
Dim outputString As String
Dim outputFilePath As String
Dim outputWorkbook As Workbook
' 设置输入范围
Set inputRange = Range("A1:A10")
' 创建输出范围
Set outputRange = Range("B1")
For i = 1 To inputRange.Rows.Count
For j = 1 To inputRange.Columns.Count
outputRange.Offset(j - 1, i - 1).Value = inputRange(i, j).Value
Next j
Next i
' 处理输出字符串
For i = 1 To outputRange.Columns.Count
outputString = outputString & outputRange(1, i).Value & ","
Next i
outputString = Left(outputString, Len(outputString) - 1) ' 去掉最后一个逗号
' 写入CSV文件
outputFilePath = "C:\output.csv" ' 文件路径
Set outputWorkbook = Workbooks.Add
outputWorkbook.ActiveSheet.Cells(1, 1).Value = outputString
outputWorkbook.SaveAs Filename:=outputFilePath, FileFormat:=xlCSV, CreateBackup:=False
outputWorkbook.Close SaveChanges:=False
End Sub
```
你需要将代码中的输入范围和输出文件路径修改为你需要的值。此外,代码中假设输出范围的第一行是标题行。如果你不需要标题行,可以将输出字符串的第一行改为:
```vb
' 处理输出字符串
For i = 1 To outputRange.Columns.Count
outputString = outputString & outputRange(1, i).Value
If i < outputRange.Columns.Count Then outputString = outputString & ","
Next i
```
阅读全文