Hap*_*aMO 7 vba ms-word comma word-vba
我在活动窗口标题栏中的parens之间提取文本.那部分工作得很好(感谢我之前收到的一些帮助!).现在我想创建两个单独的宏 - 一个只返回第一个名称,另一个只返回姓氏.
我的活动窗口标题栏看起来像这样:
左边有一些文字(HENDERSON,TOM)右边有一些文字(逗号后面没有空格)
姓氏宏工作得很好.它看起来像这样:
Sub a1LastName()
'Extract last name of patient from title bar (between parens)
Dim strPatientName As String
Dim OpenPosition As Integer '(open paren marker)
Dim closeposition As Integer '(close paren marker)
OpenPosition = InStr(ActiveDocument.ActiveWindow.Caption, "(")
closeposition = InStr(ActiveDocument.ActiveWindow.Caption, ")")
strPatientName = Mid(ActiveDocument.ActiveWindow.Caption, _
OpenPosition + 1, closeposition - OpenPosition - 1)
Dim c As Long
c = InStr(strPatientName, ",")
strPatientName = Left(strPatientName, c - 1)
Selection.TypeText strPatientName
End Sub
Run Code Online (Sandbox Code Playgroud)
第二个宏与第一个宏相同,只是倒数第二行的代码有一个"Right"而不是"Left"指令:
Sub a1FirstName()
'Extract first name of patient from title bar (between parens)
Dim strPatientName As String
Dim OpenPosition As Integer '(open paren marker)
Dim closeposition As Integer '(close paren marker)
OpenPosition = InStr(ActiveDocument.ActiveWindow.Caption, "(")
closeposition = InStr(ActiveDocument.ActiveWindow.Caption, ")")
strPatientName = Mid(ActiveDocument.ActiveWindow.Caption, _
OpenPosition + 1, closeposition - OpenPosition - 1)
Dim c As Long
c = InStr(strPatientName, ",")
strPatientName = Right(strPatientName, c - 1)
Selection.TypeText strPatientName
End Sub
Run Code Online (Sandbox Code Playgroud)
这是我的问题:"名字"宏总是返回姓氏减去前四个字符,后跟第一个名字,而不是简单的第一个名字.
我能在谷歌任何地方找到的唯一例子都是专门用于Excel的.我通过我的VBA手册结合起来,他们都提供了类似的例子,就像我用来提取角色右边的文本一样.
我究竟做错了什么?
您可以使用Split()从文本的逗号分隔部分创建数组,然后访问第一部分或第二部分:
Sub a1LastName()
Dim strPatientName As String
strPatientName = ParensContent(ActiveDocument.ActiveWindow.Caption)
If strPatientName Like "*,*" Then
Selection.TypeText Trim(Split(strPatientName, ",")(0))
End If
End Sub
Sub a1FirstName()
Dim strPatientName As String
strPatientName = ParensContent(ActiveDocument.ActiveWindow.Caption)
If strPatientName Like "*,*" Then
Selection.TypeText Trim(Split(strPatientName, ",")(1))
End If
End Sub
'Utility function: find and return text enclosed by ()
' Return empty string if no () found
Function ParensContent(txt) As String
Dim rv As String, pos As Long, pos2 As Long
If txt Like "*(*)*" Then
pos = InStr(1, txt, "(")
pos2 = InStr(pos, txt, ")")
rv = Mid(txt, pos + 1, (pos2 - pos) - 1)
End If
ParensContent = rv
End Function
Run Code Online (Sandbox Code Playgroud)