首先,我对使用 VBA for Access 进行编码完全陌生,因此可能存在很多错误。但无论如何,我对名字和中间名首字母有一些疑问。目前,名称的格式为 [lastName,firstName middleInitial] 中的字符串,我有 3 个文本框,分别标记为 lastName firstName 和 middleInitial。下面的代码应该做的是将字符串分成三个适当的框,但它挂在名字上,它不知道如何在空格处停下来或者它会切断一些字符,而中间的首字母在哪里它仅在它们具有中间名首字母时才有效,但如果找不到中间名首字母,则会抛出错误。我一直在绞尽脑汁试图弄清楚,因此我陷入了僵局,在这里问。
非常感谢!
Private Sub cbxMbr_AfterUpdate()
If Not Me.opgMngRoster.Value = 1 Then
'Member's Last Name
Dim lastName As String
lastName = Left(cbxMbr.Text, (InStr(1, cbxMbr.Text, ",") - 1))
Me.txtLastName.Value = lastName
'Member's First Name
Dim firstName As String
firstName = Mid(cbxMbr.Text, InStr(1, cbxMbr.Text, " "), (Len(cbxMbr.Text) - InStr(1, cbxMbr.Text, " ")))
Me.txtFirstName.Value = firstName
'Member's Middle Initial
Dim midName As String
midName = Mid(cbxMbr.Text, InStr(InStr(1, cbxMbr.Text, " ") + 1, cbxMbr.Text, " "))
If midName = vbNullString Then
Me.txtMidInit.Value = " "
Else
Me.txtMidInit.Value = midName
'DoCmd.RunSQL "SELECT MEMBER ROSTER WHERE "
End If
End If
End Sub
您可以使用拆分:
' "Duck, Donald D."
' "Duck, Donald"
Me!txtLastName.Value = Split(Me!cbxMbr.Value, ",")(0)
' Duck
Me!txtFirstName.Value = Split(Trim(Split(Me!cbxMbr.Value, ",")(1)), " ")(0)
' Donald
Me.txtMidtInit.Value = Split(Trim(Split(Me!cbxMbr.Value, ",")(1)) & " ", " ")(1)
' D. or zero-length string.
古斯塔夫响应得到结果:'D, 您需要将第一个括号内的 1 从 1 更改为 2,如下所示:
Me.txtMidtInit.Value = Split(Trim(Split(Me!cbxMbr.Value, ",")(2)) & " ", " ")(1) ' D. 或零长度字符串。