【问题标题】:How to add multiple string values to a cell in a excel sheet using vba如何使用vba将多个字符串值添加到Excel工作表中的单元格
【发布时间】:2016-10-06 11:47:04
【问题描述】:

我下面的代码检查列 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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您可以使用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】:

    将字符串存储在字符串变量中,而不是将其直接写入单元格。比如:

    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
    

    【讨论】:

      【解决方案3】:

      只需使用&amp; 喜欢

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多