Excelmacros保存表格作为CSV与特定的分隔符和附件

我是一个完全虚拟的VB和EXCEL,试图把我在这里find的2个macros组合成1,但显然做了一些可怕的错误,现在我卡住了。首先,我只是用这个macros(保存它在personal.xlsb中,以便能够在任何工作簿中使用它)

Sub CSVFile() Dim SrcRg As Range Dim CurrRow As Range Dim CurrCell As Range Dim CurrTextStr As String Dim ListSep As String Dim FName As Variant FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv") ListSep = ";" If Selection.Cells.Count > 1 Then Set SrcRg = Selection Else Set SrcRg = ActiveSheet.UsedRange End If Open FName For Output As #1 For Each CurrRow In SrcRg.Rows CurrTextStr = ìî For Each CurrCell In CurrRow.Cells CurrTextStr = CurrTextStr & """" & GetUTF8String(CurrCell.Value) & """" & ListSep Next While Right(CurrTextStr, 1) = ListSep CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1) Wend Print #1, CurrTextStr Next Close #1 End Sub 

那加GetUTF8String函数代码。 现在工作正常。 然后我想,为什么不试试我的有限(这是一个严重的轻描淡写)vb的理解,添加了下面的代码,并将CSVFile子变成一个函数,然后我从下面的子调用,输出文件名为一个参数(用来代替FName = Application.GetSaveAsFilename)。 我想是的,这个代码会自动保存所有的页面,现在我们只需要确保在保存每个页面之前运行编码和分隔符/围栏设置function。 这似乎不对,但我想嘿为什么不试试..

 Public Sub SaveAllSheetsAsCSV() On Error GoTo Heaven ' each sheet reference Dim Sheet As Worksheet ' path to output to Dim OutputPath As String ' name of each csv Dim OutputFile As String Application.ScreenUpdating = False Application.DisplayAlerts = False Application.EnableEvents = False ' Save the file in current director OutputPath = ThisWorkbook.Path If OutputPath <> "" Then Application.Calculation = xlCalculationManual ' save for each sheet For Each Sheet In Sheets OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv" ' make a copy to create a new book with this sheet ' otherwise you will always only get the first sheet Sheet.Copy ' this copy will now become active CSVFile(OutputFile) ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False ActiveWorkbook.Close Next Application.Calculation = xlCalculationAutomatic End If Finally: Application.ScreenUpdating = True Application.DisplayAlerts = True Application.EnableEvents = True Exit Sub Heaven: MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _ "Source: " & Err.Source & " " & vbCrLf & _ "Number: " & Err.Number & " " & vbCrLf & _ "Description: " & Err.Description & " " & vbCrLf GoTo Finally End Sub 

保存了这个,并且我设法实现了非常不同的东西。 打开任何工作簿时,该macros将运行并从该特定工作簿中打开我的工作表作为csv文件(不保存它们)。 现在我就像爱丽丝梦游仙境。 它是如何运行的文件打开? 这是不可取的,所以我回到macros代码,并将其改回到csvfile子。 那么没有帮助,不知道我在那里做了什么,肯定是编辑同一个macros…所以我删除了macros,模块,我无法想象现在的东西,但它仍然在运行+我得到这个警告macros被禁用。 无法摆脱它! 现在小伙子们,我很抱歉从我身边完全缺乏专业性,这只是一个客户的小小的忙,没有浪费大量的时间学习VB,因为我的老板不喜欢这样的…我当然,如果在设置分隔符和shell之后自动保存纸张的目标,我感兴趣。 而在这一刻,我对如何摆脱这个macros以及它隐藏的位置非常感兴趣。我做了什么? 感谢您的耐心等待!

我认为问题在于线路

 OutputPath = ThisWorkbook.Path 

因为您正在从存储在您的XLSTART文件夹中的personal.xlsb中运行该文件,所以它已经在相同的位置创build了CSV文件。 当Excel启动时,它将尝试加载它在该位置find的任何文件。

只需find您的XLSTART文件夹,并删除您在那里find的任何CSV文件。

尝试使用

 OutputPath = ActiveWorkbook.Path 

XLSTART文件夹的位置,取决于您的系统,可能是这样的:

 C:\Users\YOURNAME\AppData\Roaming\Microsoft\Excel\XLSTART