在值之前修剪空白区域

时间:2015-07-02 20:58:48

标签: excel vba excel-vba

我在修剪空格字符时遇到问题。当我输入一个值并在Excel中的值之前和之后给出空格时,我看到它周围的空格但我不应该看到那些额外的空格。

我想删除这些空格,但我不知道如何实现这一点,这是我目前得到的输出:

ServerName = "       testing     "          

但生成的输出应该是这样的......

ServerName = "testing"  

以下是我在我的项目中使用的代码:

If Sheets(Itm).Cells(i, 2) = "Required1" Then
    MsgBox "Enter the value for required field : " & Sheets(Itm).Cells(i, 1)
    Return
End If

Value = Replace(Sheets(Itm).Cells(i, 4).Value, vbLf, " ")
'Value = Sheets(Itm).Cells(i, 4).Value

2 个答案:

答案 0 :(得分:0)

替换:

Print #1, Sheets(Itm).Cells(i, 1) & "=" & Value

使用:

Print #1, Replace(Sheets(Itm).Cells(i, 1) & "=" & Value," ","")

答案 1 :(得分:0)

试试这个(未经测试)

Value = Trim(Sheets(Itm).Cells(i, 4).Value)
Value = Application.WorksheetFunction.Clean(Value)
Print #1, Sheets(Itm).Cells(i, 1) & "=" & Value

以下是了解其工作原理的示例代码...

Sub sample()
    Dim sample As String

    sample = "Sid"

    Debug.Print Len(sample) '<~~ This will give you 3

    sample = " " & vbNewLine & sample & vbNewLine & vbCrLf & vbLf

    Debug.Print Len(sample) '<~~ This will give you 11

    sample = Trim(sample)

    Debug.Print Len(sample) '<~~ This will give you 10

    sample = Application.WorksheetFunction.Clean(sample)

    Debug.Print Len(sample)  '<~~ This will give you 3
End Sub