0

次のようなスプレッドシートがあります。

Group   | Name   | Title
-----------------------------------
X         WS       -
X         DH       -
X         M        -
X         DH       -
X         WS       -

名前のすべてのセルをループして、正しいタイトルを追加するだけでなく、そこにあるイニシャルをフルネームに置き換えたいと思います。私のスクリプトは、文字列を正確に比較して if ステートメントに入ることができません

Sub enterNameAndTitle()

    lastCell = InputBox("Last cell")
    rInitials = InputBox("Initials")
    rFullName = InputBox("Full Name")
    rTitle = InputBox("Title")

    Dim cell As Range

    For Each cell In Range("b2:b" & lastCell).Cells

        MsgBox (cell.Text & " : " & rInitials)

        If StrComp(UCase(cell.Value), UCase(rInitials)) = 0 Then
            cell.Value = rFullName
            ActiveSheet.Cells(cell.Row, cell.Column + 1).Value = rTitle
        End If

    Next cell

End Sub

したがって、最初にデータを収集してから、すべての値をループします。私が間違っていることを誰かが知っていますか?文字列を正確に比較しないのはなぜですか?

4

2 に答える 2

0

何も問題はありませんが、試してみたいことが2つあります

1 つは、TRIM を使用して、どちらの文字列にも先頭または末尾の空白がないことを確認することです。

2 つ目は、if を次のように変更することです。 if(ucase(trim(cell.value))=ucase(trim(rInitials)))

于 2013-05-21T19:28:18.643 に答える
0

問題は異なる型の 1 つであり、私にとってはうまくいくと思われる唯一の方法は、CStr() を使用して両方の変数を型 String として再キャストすることでした。

Sub enterNameAndTitle()

    Dim lastCell As String
    lastCell = InputBox("Last cell")

    'Cast to string
    Dim rInitials As String

    rInitials = CStr(InputBox("Initials"))
    Dim rFullName As String
    rFullName = InputBox("Full Name")
    Dim rTitle As String
    rTitle = InputBox("Title")

    Dim cell As Range

    For Each cell In Range("b2:b" & lastCell).Cells

        Dim cellText As String

        'Cast to string
        cellText = CStr(cell.Text)

        If (Trim(UCase(cell.Value)) = Trim(UCase(rInitials))) Then
            MsgBox ("test1")
            cell.Value = rFullName
            ActiveSheet.Cells(cell.Row, cell.Column + 1).Value = rTitle
        End If

    Next cell

End Sub
于 2013-05-21T21:10:41.960 に答える