首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >引用双引号中的单元格值: Excel VBA宏

引用双引号中的单元格值: Excel VBA宏
EN

Stack Overflow用户
提问于 2017-03-27 09:29:47
回答 3查看 3.9K关注 0票数 5

我想将双引号放在特定列中的所有单元格中。我编写了代码来放置双引号,但问题是它在值周围放置了3个双引号。

代码语言:javascript
运行
复制
 For Each myCell In ActiveWorkbook.Sheets("Sheet1").Range("B:B")
        If myCell.Value <> "" Then
            myCell.Value = Chr(34) & myCell.Value & Chr(34)
        End If
 Next myCell

基本要求是将excel文件按B列拆分,并将其保存为CSV文件。

在分割字段中,B和D列的值必须用双引号括起来。

完整法典:

代码语言:javascript
运行
复制
Option Explicit

Sub ParseItems()
Dim LR As Long, Itm As Long, MyCount As Long, vCol As Long
Dim ws As Worksheet, MyArr As Variant, vTitles As String, SvPath As String
Dim myCell As Range, transCell As Range

'Sheet with data in it
   Set ws = Sheets("Sheet1")

'Path to save files into, remember the final \
    SvPath = "D:\SplitExcel\"

'Range where titles are across top of data, as string, data MUST
'have titles in this row, edit to suit your titles locale
'Inserting new row to act as title, copying the data from first row in title, row deleted after use
    ws.Range("A1").EntireRow.Insert
    ws.Rows(2).EntireRow.Copy
    ws.Range("A1").Select
    ws.Paste
    vTitles = "A1:Z1"

'Choose column to evaluate from, column A = 1, B = 2, etc.
   vCol = 2
   If vCol = 0 Then Exit Sub

'Spot bottom row of data
   LR = ws.Cells(ws.Rows.Count, vCol).End(xlUp).Row

'Speed up macro execution
   Application.ScreenUpdating = False

'Get a temporary list of unique values from key column
    ws.Columns(vCol).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=ws.Range("EE1"), Unique:=True

'Sort the temporary list
    ws.Columns("EE:EE").Sort Key1:=ws.Range("EE2"), Order1:=xlAscending, Header:=xlYes, _
       OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

'Put list into an array for looping (values cannot be the result of formulas, must be constants)
    MyArr = Application.WorksheetFunction.Transpose(ws.Range("EE2:EE" & Rows.Count).SpecialCells(xlCellTypeConstants))

'clear temporary worksheet list
    ws.Range("EE:EE").Clear

'Turn on the autofilter, one column only is all that is needed
    'ws.Range(vTitles).AutoFilter

'Loop through list one value at a time
    For Itm = 1 To UBound(MyArr)
        ws.Range(vTitles).AutoFilter Field:=vCol, Criteria1:=MyArr(Itm)
        'transCell = ws.Range("A2:A" & LR)
        ws.Range("A2:A" & LR).EntireRow.Copy
        Workbooks.Add
        Range("A1").PasteSpecial xlPasteAll
        Cells.Columns.AutoFit
        MyCount = MyCount + Range("A" & Rows.Count).End(xlUp).Row - 1



        For Each myCell In ActiveWorkbook.Sheets("Sheet1").Range("B:B")
            If myCell.Value <> "" Then
               myCell.Value = Chr(34) & myCell.Value & Chr(34)
            End If
        Next myCell



        ActiveWorkbook.SaveAs SvPath & "po" & MyArr(Itm) & ActiveWorkbook.Sheets("Sheet1").Range("D1") & "." & Date2Julian(Date), xlCSV, local:=False
        ActiveWorkbook.Close False

        ws.Range(vTitles).AutoFilter Field:=vCol
    Next Itm

'Cleanup
    ws.Rows(1).EntireRow.Delete
    ws.AutoFilterMode = False
    Application.ScreenUpdating = True
End Sub

Function Date2Julian(ByVal vDate As Date) As String

    Date2Julian = Format(DateDiff("d", CDate("01/01/" _
                  + Format(Year(vDate), "0000")), vDate) _
                  + 1, "000")



End Function

样本输入数据:

代码语言:javascript
运行
复制
24833837    8013    70  1105
25057089    8013    75  1105
25438741    8013    60  1105
24833837    8014    70  1106
25057089    8014    75  1106
25438741    8014    60  1106

预期输出是用以下数据创建的两个文件

档案1:

代码语言:javascript
运行
复制
24833837,"8013",70,1105
25057089,"8013",75,1105
25438741,"8013",60,1105

档案2:

代码语言:javascript
运行
复制
24833837,"8014",70,1106
25057089,"8014",75,1106
25438741,"8014",60,1106

结果产出:

档案1:

代码语言:javascript
运行
复制
24833837,"""8013""",70,1105
25057089,"""8013""",75,1105
25438741,"""8013""",60,1105

文件2相同

帮帮忙吧。:)

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-03-27 10:12:13

Afaik,在使用普通的“另存为csv"-procedure时,没有简单的方法来欺骗Excel使用数字周围的引号。但是,您可以使用VBA以您喜欢的任何csv格式保存。

https://support.microsoft.com/en-us/help/291296/procedure-to-export-a-text-file-with-both-comma-and-quote-delimiters-in-excel中的代码为例

只需添加if-语句即可确定是否使用引号。

代码语言:javascript
运行
复制
' Write current cell's text to file with quotation marks.
If WorksheetFunction.IsText(Selection.Cells(RowCount, ColumnCount)) Then
    Print #FileNum, """" & Selection.Cells(RowCount, _
        ColumnCount).Text & """";
Else
    Print #FileNum, Selection.Cells(RowCount, _
        ColumnCount).Text;
End If

如果您的数字是用前面的‘(单引号)输入的,WorksheetFunction.IsText将识别它们为文本。

您需要调整示例,以便使用代码中预先给定的文件名导出所需的范围。

票数 2
EN

Stack Overflow用户

发布于 2017-03-27 10:26:36

这个小潜艇能满足你的需要。只需给它一个文件名fname,可以导出为csv rg的范围和列号column_with_quotes --类似于此,但范围适合:

代码语言:javascript
运行
复制
save_as_csv_with_optional_quotes SvPath & "po" & MyArr(Itm) & ActiveWorkbook.Sheets("Sheet1").Range("D1") & "." & Date2Julian(Date), Range("A1:C5"), 2

这是潜艇:

代码语言:javascript
运行
复制
Sub save_as_csv_with_optional_quotes(fname As String, rg As Range, column_with_quotes As Long)
    Dim ff, r, c As Long
    Dim loutput, cl As String

    ff = FreeFile
    Open fname For Output As ff

        For r = 1 To rg.Rows.Count
            loutput = ""
            For c = 1 To rg.Columns.Count
                If loutput <> "" Then loutput = loutput & ","
                cl = rg.Cells(r, c).Value
                If c = column_with_quotes Then cl = Chr$(34) & cl & Chr$(34)
                loutput = loutput & cl
            Next c
            Print #ff, loutput
        Next r
    Close ff
End Sub
票数 2
EN

Stack Overflow用户

发布于 2017-03-27 09:46:10

问题是这条线。

代码语言:javascript
运行
复制
myCell.Value = Chr(34) & myCell.Value & Chr(34)

当您作为CSV导出时,您要添加的引号将再次被引用,因此值的每个边都有三个引号。我认为一个更好的选择是将myCell的数字格式改为文本,而不是数字。我还没有试过这个,但我认为把它改成这个应该会有帮助。

代码语言:javascript
运行
复制
myCell.Value = Chr(39) & myCell.Value

Chr(39)是一个撇号,当您作为单元格值的第一个字符输入它时,它强制格式为文本。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43042674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档