簡體   English   中英

如何使用VBA將多個字符串值添加到Excel工作表中的單元格

[英]How to add multiple string values to a cell in a excel sheet using 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

將字符串存儲在字符串變量中,而不是將其直接寫入單元格中。 就像是:

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

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

只需使用&喜歡

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM