使用VBA将单元格区域导出到新的.csv文件并保存而不覆盖 [英] Export a cell range into a new .csv file with VBA and save it without overwriting
问题描述
我要做的就是复制,将单元格区域粘贴到新的CSV文件中,然后使用VBA保存新文件.我可能会将此VBA多次用于此文件.所以,我想用一个数字来保存文件.
All I am trying to do is copy, paste a cell range into a new CSV file and save the new file with VBA. I will might use this VBA for this file many times. So, I would like to make it save the files with a number.
我正在使用下面的代码,并且可以正常工作:
I am using the code below and it is working:
Sub ExportRangetoFile()
Dim Rng As Range
Dim WorkRng As Range
Dim xFile As Variant
Dim xFileString As String
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ActiveSheet.Copy
Application.ActiveSheet.Cells.Clear
WorkRng.Copy Application.ActiveSheet.Range("A1")
Set xFile = CreateObject("Scripting.FileSystemObject")
ActiveWorkbook.SaveAs Filename:="C:\Users\User\Desktop\Range.csv", FileFormat:=xlCSV, CreateBackup:=False
End Sub
具有从原始excel文件中选择的单元格范围的保存文件称为范围.我想更改代码,并使其保存文件而不会覆盖其他任何文件.
The saved file with the cell range I selected from the original excel file is called Range. I want to change the code and make it save the files without overwriting any other file.
我认为这是我应该更改的部分:
I presume this is the part I should change :
ActiveWorkbook.SaveAs Filename:="C:\Users\User\Desktop\Range.csv", FileFormat:=xlCSV, CreateBackup:=False
我试图将"False"更改为"True",但没有用.也许是出于另一个原因.
I tried to change the "False" to "True" but it did not work. Maybe for another reason though.
推荐答案
我只是重新阅读了?再次.您需要的是一种获取新编号并将其添加到文件名的方法.
I just re-read the ? again. What you need is a way to get a new number and add it to the file name.
FiNum = ... 'get file number from a text file
FiName = "C:\Users\User\Desktop\Range" & FiNum & ".csv"
ActiveWorkbook.SaveAs Filename:=FiName, FileFormat:=xlCSV, CreateBackup:=False
FiNum = FiNum + 1
Call WriteToFile(FiNum) ... 'write file number back to text file
Sub WriteToFile(ByVal FiNum As Long)
Open "C:\FiNumber.txt" For Output As #1
Print #1, CStr(FiNum) 'print as string for optimum results
Close #1
End Sub
这篇关于使用VBA将单元格区域导出到新的.csv文件并保存而不覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!