Vba 如何将单元格中的字符串与inputBox()中的字符串进行比较
我有一张这样的电子表格:Vba 如何将单元格中的字符串与inputBox()中的字符串进行比较,vba,excel,Vba,Excel,我有一张这样的电子表格: Group | Name | Title ----------------------------------- X WS - X DH - X M - X DH - X WS - 我想循环遍历名称中的所有单元格,除了添加正确的标题外,还要用它们的全名替换其中的首字母。我的脚本无法准确比较字符串并进入if语句: Sub
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
所以我首先收集数据,然后循环遍历所有的值。有人知道我做错了什么吗?为什么它不能准确地比较字符串?我没有发现任何错误,但有两件事我会尝试 一种是使用TRIM来确保字符串没有前导空格或尾随空格
第二个是将if改为
if(ucase(trim(cell.value))=ucase(trim(rInitials))
问题是不同的类型之一,唯一对我有效的方法是使用CStr()将两个变量重新转换为类型字符串
我试过这个,但它总是返回“false”,我不知道为什么它不起作用!我必须对这两个字符串使用CStr()来强制它们的类型。我认为这是因为cell.Value返回一个变量对象。
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