2013-03-27 103 views
2

我想从excel中创建一个CSV文件,其中字段中的所有数据将位于双引号内。 我发现这个代码从一个类似的问题,它几乎工程...excel中的CSV文件与双引号内的字段

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") 

If FName <> False Then 
    ListSep = Application.International(xlListSeparator) 
    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 & """" & CurrCell.Value & """" & ListSep 
    Next 
    While Right(CurrTextStr, 1) = ListSep 
     CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1) 
    Wend  
    Print #1, CurrTextStr  
    Next  
    Close #1  
    End If 
End Sub 

它让我保存在一个CSV选定的领域,结果是这样的:

"A1","B1","C3" 
"A2","B2","C3" 

我需要它也做的就是把一个逗号的最后一个字段后太喜欢这样的:

"A1","B1","C3", 
"A2","B2","C3", 

我不知道这种代码的想法,并可以使用一些帮助。

此外,如果这项工作如何保存在Excel表中的宏,所以我可以在任何时候使用它,我需要它。

感谢 约翰

回答

1

我觉得这段代码被删除每行列表分隔/逗号。尝试删除这三行,看看是否修复它。

While Right(CurrTextStr, 1) = ListSep 
    CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1) 
Wend 

将包含在你的“个人” Excel工作簿此脚本,它总是会提供给你,无论代码模块哪些文件是打开的。

否则,只需将此代码模块放置在所需的工作簿代码模块中,并确保保存为XLSM。

+0

它做了伎俩谢谢你队友。 :) 我想“将包含此脚本的代码模块放在您的”个人“Excel工作簿中,但我不知道该怎么做。 :( 我做了到现在为止是: - ALT + F11 - 粘贴代码 - 关闭并返回到Excel - Alt + F8运行和执行脚本 我第一次使用宏,我在这里丢失了,你能否给我一个虚拟的假人 再次感谢您的帮助 – John 2013-03-27 18:46:34

+0

John,这里是一个关于从Excel MVP Ron de Bruin创建“PERSONAL”工作簿的概述http://www.rondebruin.nl /personal.htm – 2013-03-27 18:52:49

相关问题