我有一张看起来像这样的电子表格:
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
所以我首先收集数据,然后循环遍历所有值。有谁知道我做错了什么?为什么不准确地比较字符串?
答案 0 :(得分:0)
我没有看到任何错误,但我会尝试两件事
一种方法是使用TRIM确保两个字符串都没有前导或尾随空白
第二个是将if更改为if(ucase(trim(cell.value))=ucase(trim(rInitials)))
答案 1 :(得分:0)
问题是不同类型之一,对我来说似乎唯一有用的方法是使用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