Excel自定义格式添加"记录之前和之后

时间:2017-01-20 11:03:34

标签: excel vba excel-vba formatting

我想在excel中的记录之前添加"
我还希望在每条记录之后添加"|

我在VBA中使用自定义格式。

我的格式为"\""@\""|"

我的结果是

"""1111""|" """Noel Gallagher""|"   |   """Individual""|"   """Employee""|" """111""|"  """Main Road""|"    """Town""|" """""|" """County"|"    """City""|" |   |   |   |   |   |   |   |   |       |   |   |   |   |   |   """IE""|"   """AAA""|"  """Value""|"

我需要

"1111"| "Noel Gallagher"|""|"Individual"|"Employee"|"111"|"Main Road"|"Town"|""|"County"|"City"|""|""|""|""|""|""|""|""|""|""|""|""|""|""|""|"IE"|"AAA"|"Value"|

我似乎无法通过自定义格式获得正确的结果。有没有替代方案?

3 个答案:

答案 0 :(得分:1)

\“@ \”|的自定义格式应该这样做吗?

所以在vba中......那将是:

范围(“xxx:yyy”)。NumberFormat =“\”“@ \”“|”

答案 1 :(得分:1)

警告以下代码将更改单元格内容,而不是将格式化应用于单元格。因此,具有公式的单元格将转换为文本。

目前它将在所有当前选定的单元格上运行,但如果需要,将其更改为在特定范围内运行是一件简单的事情。

Sub add_quotes_and_pipe_to_selected_cells()
    vbQt = """"
    Dim rng As Range
    Set rng = Selection ' or this could be a range such as = range("A2:X50")
    For Each c In rng.Cells
        c.Cells(1, 1) = vbQt & c.Cells(1, 1).Text & vbQt & "|"
    Next
    Set rng = Nothing
End Sub

答案 2 :(得分:1)

现在我对您的问题有了更好的了解,下面的代码应该会为您提供您所追求的内容。

这将采用所选范围并将其(使用文本限定符和分隔符要求)导出到x驱动器上名为outputfile.txt的文件中。根据需要更改此项。这意味着您不需要使用Excel保存文件,这一切都在宏中完成。

我已经假设您不希望/需要文件每行的最后一个管道。如果情况并非如此并且是必需的,请删除将其剥离的行(它开始If Right(outputline, 1)...

Sub export_range_with_quotes_and_pipe()
    vbQt = """"
    delim = "|"
    exportfilename = "x:\outputfile.txt"
    Dim rng As Range
    Set rng = Selection ' or this could be a range such as = range("A2:X50")
    ff = FreeFile
    'create text file for output
    Open exportfilename For Output As ff
    'read each row from range
    For Each r In rng.Rows
        outputline = ""
        'read each cell in row R
        For Each c In r.Cells
            'build outputline from each cell in row R
            outputline = outputline & vbQt & c.Cells(1, 1).Text & vbQt & delim
        Next
        'strip last pipe delimiter as not required
        If Right(outputline, 1) = delim Then outputline = Left(outputline, Len(outputline) - 1)
        'send outputline to file
        Print #ff, outputline
    Next
    ' close file
    Close ff
    Set rng = Nothing
End Sub
相关问题