将 sheet 中的列保存到 CSV 文件

Saving column from sheet to CSV file

我想从 sheet2 中提取 A 列并将其复制到新的 CSV 文件中。

我可以使用此 Sheets("Sheet2").Copy.

将整个 sheet (Sheet2) 复制并保存到 CSV 文件

当我尝试复制并保存 Sheet2 中的 A 列时,它会复制并保存整个工作簿。

Sub Save_Sheet2_To_CSV()

Dim MyPath As String
Dim MyFileName As String

MyPath = Range("J10") & "\"
MyFileName = Range("J13")

If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"

ActiveWorkbook.Sheets("Sheet2").Columns(1).Copy

ActiveWorkbook.SaveAs FileName:=MyPath & MyFileName, FileFormat:=xlCSVUTF8, CreateBackup:=False

ActiveWorkbook.Close

MsgBox "Sheet2 Export Successful!"

End Sub

请测试下一个更新的代码:

Sub Save_Sheet2_To_CSV()
 Dim MyPath As String, MyFileName As String, rng As Range

 MyPath = Range("J10").Value
 MyFileName = Range("J13").Value

 If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
 If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"

 ActiveWorkbook.Sheets("Sheet2").copy 'it creates a new workbook containing only Sheet 2 shet content
 Set rng = ActiveWorkbook.Sheets(1).UsedRange
 rng.Offset(0, 1).Clear 'keep only the first column

 ActiveWorkbook.saveas filename:=MyPath & MyFileName, FileFormat:=xlCSVUTF8, CreateBackup:=False
 ActiveWorkbook.Close

 MsgBox "Sheet2 Export Successful!"
End Sub