首页 > 解决方案 > cell.Value 未检索单元格中的回车符

问题描述

我的 Excel 单元格有回车符 \ 换行符,但是当读入 cell.value 时,回车符消失了。有没有办法处理这个问题,以便我可以确定换行符在哪里(不修改我的源 Excel 工作表数据)?

在下面的代码中(在这个线程的底部),我希望 ProductText 变量设置为:

Orange<CR> 
Red<CR>
Yellow<CR>

where<cr>表示回车。

当我从 Excel 单元格复制到记事本时,我可以确认换行符存在。

但是在VBA中,ProductText填充为:“Orange Red Yellow”并且回车符消失了。

'YOU MAY SKIP TO THE ******************************************* for the purposes of this post

Public Sub ProcessCharmMingFile(Excel_UNC_Path As String)

    Dim src As Workbook

    Dim ProdPushWorkbook As Workbook

    Set ProdPushWorkbook = ActiveWorkbook


    Set src = Workbooks.Open(Excel_UNC_Path, True, True)

    Dim c As Range
    Dim r As Range
    Dim LastRow As Long

    Dim Text As String

    src.Sheets("Table 1").Activate

    src.ActiveSheet.Range("A1").Select
    LastRow = src.ActiveSheet.Range("A30000").End(xlUp).Row
    Text = LastRow
    Text = "A1:T" + CStr(Text)

    Set r = Range(Text)

    Dim i As Integer

    For i = 1 To MaxItems
        PONumber(i) = ""
    Next


    Dim PageCounter As Integer
    PageCounter = 0
    RecordCounter = 0


    Dim ProductText As String
    Dim QtyText As String
    Dim HeatText As String


       '***********************************************************
       '***********************************************************
       '***********************************************************

    For Each c In r
        If c.Value = "ALLIED FITTING Product Code" Then
            PageCounter = PageCounter + 1
            ProductText = c.Offset(1, 0).Value
            HeatText = c.Offset(1, 1).Value
            QtyText = c.Offset(1, 2).Value

        End If
    Next

       '***********************************************************
       '***********************************************************
       '***********************************************************



    If RecordCounter = 0 Then
        Call AbortFileProcessing("No Valid Reoords Dected", False, ProdPushWorkbook)
    End If


    src.Close


End Sub

标签: excelvbarange

解决方案


问题是您需要换行以使行在单元格中单独显示。

VBA 对此有适当的常量:

Sub CRLFString()
Dim str As String

str = "hello" & vbCr & "world!"
Range("A1").Value = str 'Reads: "helloworld!" - Wrap Text won't change this.

str = "hello" & vbLf & "world!"
Range("A2").Value = str 

str = "hello" & vbCrLf & "world!"
Range("A3").Value = str 'Both of these read
    'hello
    'world!

End Sub

但是,如果您使用Debug.Print所有三个字符串来输出这些字符串,那么它们将按预期在 2 行上。

简而言之:添加换行符,否则您会得到问题中描述的结果。您可以使用ReplaceonvbCr这样做:

Sub AddLineBreaksAndOutput(str As String)
    str = Replace(str, vbCr, vbCrLf)
    Range("A4").Value = str
End Sub

Sub Test()
Dim str As String
str = "hello" & vbCr & "world!"
AddLineBreaksAndOutput str
End Sub

推荐阅读