行与字符串之间的空格

时间:2017-11-16 13:58:18

标签: excel vba excel-vba

我有这个:

| col1 | col2 | col 3 |
|    5 |   FA |   OFF |
|  107 |   FA |    ON |
|   96 |   FO |    ON |

我希望MsgBox像这样的每一行

Dim str As String
Dim r As Long

r = 2
While Celles(r,1).Value <> ""
    str = Rows(r)                    ' don't know how get row with space between items
    MsgBox str
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec("""C:\mypath\prog.exe"" " & str)

    r = r+1
Wend

我希望3个MsgBox显示为5 FA OFF 107 FA ON 96 FO ON

因此,如何正确获取行并在项目之间添加空格?

(我希望用参数调用WshShellExec

5 个答案:

答案 0 :(得分:5)

Sub x()

For i = 1 To 3
a = Application.Transpose(Application.Transpose(Range("a1:c1").Offset(i, 0).Value))
Debug.Print Join(a, "|")
Next i

End Sub

答案 1 :(得分:1)

尝试使用以下代码将每行String合并:

Option Explicit

Sub CombStringinRow()

Dim str As String
Dim r As Long, Col As Long
Dim LastCol As Long
Dim LastRow As Long

LastRow = Cells(Rows.Count, "A").End(xlUp).Row ' get last row with data from column "A"

For r = 2 To LastRow
    LastCol = Cells(r, Columns.Count).End(xlToLeft).Column ' get last column in current row

    For Col = 1 To LastCol
        If str <> "" Then
            str = str & " " & Cells(r, Col)
        Else
            str = Cells(r, Col)
        End If
    Next Col

    MsgBox str
    str = ""
Next r

End Sub

答案 2 :(得分:1)

只需从所有列中的值构建str

Dim i as Long 'HERE EDITED
For i = 0 To 2
str = str & " " & Cells(r, 1).Offset(,i) 'HERE EDITED
Next i
MsgBox str
str = ""

答案 3 :(得分:1)

请试一试......

Sub ConcatenateRowValues()
Dim x
Dim i As Long
Dim Str As String
x = Range("A1").CurrentRegion.Value
For i = 2 To UBound(x, 1)
    Str = Join(Application.Index(x, i, 0), " ")
    MsgBox Str
Next i
End Sub

答案 4 :(得分:1)

放手一搏

Sub example()
    Dim str As String
    Dim r As Long
    Dim c

    ' I'd recommend changing this to your actual sheet
    With ActiveSheet
        For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
            str = vbNullString
            For Each c In Range(.Cells(r, 1), .Cells(r, .Cells(r, .Columns.Count).End(xlToLeft).Column))
                str = str & " " & c.Value2
            Next c
            MsgBox WorksheetFunction.Trim(str)
        Next r
    End With
End Sub