用于将数据从Excel工作表自动保存到CSV文件的代码

时间:2017-01-18 21:57:21

标签: excel vba excel-vba

是否存在代码,例如每小时将数据从Sheet1中的A1:B10保存到CSV文件?

1 个答案:

答案 0 :(得分:1)

虽然这可以通过许多不同的方式完成,但这就是我要做的事情:

1)将以下子添加到新文件中。我们称之为" auto.xlsb"

Sub SaveRangeToCSV()

    Dim rng As Range
    Dim originWB As Workbook
    Dim originWS As Worksheet
    Dim newBook As Workbook
    Dim newBookWS As Worksheet

    'Open the file you want to copy the range from
    Set originWB = Workbooks.Open("path_to_file_that_contains_the_range_you_want_to_copy.xlsx")
    Set originWS = ThisWorkbook.Sheets("name_of_the_sheet_where_the_range_is")
    Set rng = originWS.Range("A1:B10")

    'Add new workbook (csv file)
    Workbooks.Add
    Set newBook = ActiveWorkbook
    Set newBookWS = newBook.Sheets(1)

    'Copy range from origin to destination (csv file)
    rng.Copy Destination:=newBookWS.Range("A1")

    'Save csv file
    newBook.SaveAs Filename:=ThisWorkbook.Path & "\output.csv"

End Sub

如果你想避免每10分钟覆盖一次output.csv,你可以,例如,将当前日期时间添加到文件名中,如下所示:

'Save csv file
newBook.SaveAs Filename:=ThisWorkbook.Path & "\output_" & Replace(Replace(Replace(Now, "/", ""), ":", ""), " ", "") & ".csv"

2)将此代码添加到Workbook_Open Sub(在VBA IDE中单击ThisWorkbook工作表,从下拉列表中选择Workbook并打开),然后保存:

Private Sub Workbook_Open()

    Call Module1.SaveRangeToCSV

End Sub

每次你点击打开文件时,都会触发SaveRangeToCSV,因此会创建csv。

3)自动执行此文件实际上取决于您的首选项和您正在使用的操作系统。我假设你在Windows上,所以最简单的方法就是在Windows中创建一个任务'任务计划程序运行" auto.xlsb"每10分钟一次。

我希望这会有所帮助。