[英]VBA to export data to CSV file (only values)
I would like to carry out the captioned task with the following codes modified from extendoffice.com (thank you).我想使用从extendoffice.com修改的以下代码来执行标题任务(谢谢)。
Sub export_data_to_CSV()
Dim Rng As Range
Dim WorkRng As Range
Dim xFile As Variant
Dim xFileString As String
Dim LR As Long
LR = Application.WorksheetFunction.CountA(Worksheets("MAIN").Range("A1:A50001"))
Set WorkRng = Application.Selection
Set WorkRng = Worksheets("MAIN").Range("A2:J" & LR)
Application.ActiveSheet.Copy
Application.ActiveSheet.Cells.Clear
WorkRng.Copy Application.ActiveSheet.Range("A1")
Set xFile = CreateObject("Scripting.FileSystemObject")
xFileString = Application.GetSaveAsFilename("", filefilter:="Comma Separated Text (*.CSV), *.CSV")
Application.ActiveWorkbook.SaveAs Filename:=xFileString, FileFormat:=xlCSV, CreateBackup:=False
End Sub
The code works fine, however, it saves all formulas and even my button to the target file.该代码工作正常,但是,它将所有公式甚至我的按钮保存到目标文件中。 What should I do to the code if I only want to save values to the target CSV file?
如果我只想将值保存到目标 CSV 文件,我应该对代码做什么?
CSV files can't have formulas or buttons by definition.根据定义,CSV 文件不能有公式或按钮。 I think you're just seeing them in the currently open Excel instance, but if you were to open the newly saved CSV file, they would not be present.
我认为您只是在当前打开的 Excel 实例中看到它们,但是如果您要打开新保存的 CSV 文件,它们将不存在。
To address your follow-up question:要解决您的后续问题:
If I want to close the target file instantly with the code, what lines should I add?
如果我想用代码立即关闭目标文件,我应该添加哪些行?
ActiveWorkbook.Close SaveChanges:=False
Here is some demo code.这是一些演示代码。 It:
它:
Sub KopyKat()
'
Sheets("Sheet1").Select 'move to sheet
Sheets("Sheet1").Copy 'copy sheet to new workbook
ActiveSheet.Cells.SpecialCells(-4123).Clear 'get rid of formulas
'then save as .csv
ActiveWorkbook.SaveAs Filename:="C:\Users\garys\Desktop\bk.csv", FileFormat _
:=xlCSVUTF8, CreateBackup:=False
ActiveWorkbook.Close 'close the new workbook
' the original workbook is now active again
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.