如何使用vba将多个字符串值添加到Excel工作表中的单元格

时间:2016-10-06 11:47:04

标签: excel excel-vba vba

我的代码检查列S和T单元格是否为空。如果单元格为空,则文本进入U列,表示不能为空。 我的问题是单元格一次可以占用一个字符串,我正在寻找一种在单个单元格中连接字符串的方法。请帮忙。感谢。

我的代码:

        For pos2 = 1 To .UsedRange.Rows.Count + 1 Step 1

            If (IsEmpty(.Cells(pos2, "S").Value) = True) Then
                .Cells(pos2, "U").Value = "Description can't be blank"
            End If

            If (IsEmpty(.Cells(pos2, "T").Value) = True) Then
                .Cells(pos2, "U").Value = "Criteria can't be blank"
            End If
       Next pos2

3 个答案:

答案 0 :(得分:0)

将字符串存储在字符串变量中,而不是直接将其写入单元格。类似的东西:

Dim strErrors as string

    For pos2 = 1 To .UsedRange.Rows.Count + 1 Step 1

        If (IsEmpty(.Cells(pos2, "S").Value) = True) Then
            strErrors = "Description can't be blank.  "
        End If

        If (IsEmpty(.Cells(pos2, "T").Value) = True) Then
            strErrors = strErrors & "Criteria can't be blank"
        End If 
        .cells(pos2, "U").value = strErrors
   Next pos2

答案 1 :(得分:0)

您可以使用String存储要在“U”列中写入的错误类型:

Dim ErrStr      As String

With Sheets("Sheet1")

    For pos2 = 1 To .UsedRange.Rows.Count + 1 Step 1
        ErrStr = "" ' reset the error string for each row

        If IsEmpty(.Cells(pos2, "S").Value) Then
           ErrStr = "Description can't be blank"
        End If

        If IsEmpty(.Cells(pos2, "T").Value) Then
            ' just to make it clearer
            If ErrStr <> "" Then
                ErrStr = ErrStr & " ; "
            End If

            ErrStr = ErrStr & "Criteria can't be blank"
        End If

        .Cells(pos2, "U").Value = ErrStr
    Next pos2

End With

答案 2 :(得分:-1)

只需使用&之类的

.Cells(pos2, "U").Value = .Cells(pos2, "U").Value & "Criteria can't be blank"