0

我正在尝试编写一个代码,如果它首先在单元格中不存在,则在前面/中间/结尾添加一行。

该单元格具有原始文本:

T - xxxxx
O - xxxxx
P - xxxxx

在某些单元格中,它没有 T/O/P,因此我需要写:

T - xxxxx
O - None
P - None

有没有办法先检查它是否没有语句,然后在前面/中间/结尾添加行?

For i = 5 To Cells(Rows.Count, "F").End(xlUp).Row

If InStr(Cells(i, "F").Value, "T -") Then
    Cells(i, "F").Value = Cells(i, "F").Value
Else
    Cells(i, "F").Value = "T - None" & vbCrLf & Cells(i, "F")
End If

If InStr(Cells(i, "F").Value, "O -") Then
    Cells(i, "F").Value = Cells(i, "F").Value
Else
    Cells(i, "F").Value = Cells(i, "F") & vbCrLf & "O - None"
End If

If InStr(Cells(i, "F").Value, "P -") Then
    Cells(i, "F").Value = Cells(i, "F").Value
Else
    Cells(i, "F").Value = Cells(i, "F") & vbCrLf & "P - None"
End If

Next i

End Sub

不确定 InStr 是做什么的。

4

1 回答 1

0

InStr函数查找字符串中指定子字符串的位置并返回其出现的第一个位置。如果未找到给定字符串的出现,则返回零。所以如果我们想检查是否String2在里面,String1我们需要评估InStr(String1, String2) > 0

对于您的解决方案,我们可以创建一个包含所有必需组件的列表,遍历所有组件并检查它们是否存在于文本中,如果没有,则为其添加默认值。所以解决方案看起来像这样。

Sub test()

Dim text As String
text = "T - xxxxx" & vbNewLine & "O - xxxxx"
Dim Components(3) As String
Components(0) = "T -"
Components(1) = "O -"
Components(2) = "P -"

text = WorksheetFunction.Trim(text)
For Each comp In Components
    If InStr(text, comp) <= 0 Then 'If component is not present
        text = text & vbNewLine & comp & " None"
    End If
Next

Debug.Print text
'prints
'T - xxxxx
'O - xxxxx
'P - None
End Sub
于 2021-06-01T11:09:07.870 回答