保存为.CSV时如何不跳过空的第一个单元格?

我有一个关于数据保存到CSV文件的方式的问题。 只有当您尝试保存第一个单元格为空的单个列时,才会出现这种情况。 您可以select整列或一组相邻的单元格。 只要将其保存到CSV文件,就会跳过前导空白单元格。 我是作为一个VBA子的一部分,但做手动保持相同的结果。 以下是我正在使用的代码和testing数据。

Sub CopyRange() 'Copy range: suppose B1 and B2 are empty, B3 to B10 are filled with anything 'eg with some numbers ActiveSheet.Range("B1:B10").Copy 'Create new workbook Workbooks.Add 'NOTE: I need to create a workbook with generic name, save the name and pass it 'to another program - just to clarity why I don't do it all in one shot at .Copy csvPath = TEMP & "\" & ActiveWorkbook.Name & ".csv" 'Paste copied data to the newly created workbook 'NOTE: so far it keeps B1 and B2 empty ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteAll, _ Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'Save the workbook as CSV ActiveWorkbook.SaveAs Filename:=csvPath, FileFormat:=xlCSV, _ ReadOnlyRecommended:=False, CreateBackup:=False 'At this point the saved file moves all data 2 cells up 'to fill the empty spaces in B1 and N2. That's the issue! End Sub 

有趣的是,如果您select多个列,则会保存空白单元格,并在正确的位置启动数据。

我尝试使用xlPasteValues而不是xlPasteAll实际上使事情变得更糟 – 现在它将跳过空单元格,即使您有超过1列,在PasteSpecial步骤。

我也尝试将它保存为xlCSVMSDOS,xlCSVWindows(都使用“\ r \ n”行尾字符)和xlCSVMac(使用“\ n |”EOL字符)。 没有工作。

请帮忙!

PS我也试图用这个方法描述的方法,但仍然没有运气。

当保存为CSV时,Excel似乎使用表格的UsedRange 。

您可以通过对范围应用某些格式来人为地扩展UsedRange。 例如,在保存之前添加此行将使其保存整个范围。

 ActiveSheet.Range("A1:A10").Interior.ColorIndex = 7 

所以只要在上下文中给你,你的sub的结尾是这样的:

 ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteAll, _ Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'Apply some color to the range so that it all gets saved in the CSV. ActiveSheet.Range("A1:A10").Interior.ColorIndex = 7 'Save the workbook as CSV ActiveWorkbook.SaveAs Filename:=csvPath, FileFormat:=xlCSV, _ ReadOnlyRecommended:=False, CreateBackup:=False 'Sheet gets saved as is with cell locations preserved. End Sub