我正试图做到这一点,以便每当单元格在电子表格上的某个范围内发生变化时,它就会触发一个脚本,以使用电子表格上的范围中的数据来编辑csv文件中的数据。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range("A1"), Range(Target.Address)) Is Nothing Then
Call ExportWorksheetAndSaveAsCSV
End If
End Sub
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs Filename:="/Users/samb/Desktop/test2.csv", FileFormat:=6
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
我把A1当作测试,但是我还没有测试Worksheet_Change是否能正常工作。我尝试手动运行ExportWorksheetAndSaveAsCSV子例程,然后返回
Run-time error 1004: Method 'SaveAs' of object '_Workbook' failed
我在网上找到了此代码,以帮助我编辑CSV文件,但似乎无法使其正常工作。
我应该指出我正在使用Mac版Excel
感谢任何人都可以提供的帮助!
编辑:
我在网上找到了该代码,该代码似乎可以正常工作,但我正在尝试对其进行修改,以在数据范围内使用它。现在,它指定第1列,单元格a等,但是我想告诉它A5:F45-有什么想法吗?
Dim My_filenumber As Integer
Dim logSTR As String
My_filenumber = FreeFile
logSTR = logSTR & Cells(1, "A").Value & " , "
logSTR = logSTR & Cells(2, "A").Value & " , "
logSTR = logSTR & Cells(3, "A").Value & " , "
logSTR = logSTR & Cells(4, "A").Value
Open "/Users/samb/Documents\test.csv" For Append As #My_filenumber
Print #My_filenumber, logSTR
Close #My_filenumber