2016-10-11 97 views
0

我想要的是宏:第一名|姓氏|用戶名類型不匹配Excel/Outlook vba

調用,即使它返回一個字符串userNameBuilder功能,並期待一個字符串

Dim firstName, lastName As String 
Set sh = ActiveSheet 
Dim counter = 0 
For Each entry In exUser.GetDirectReports() 'exUser is an exchangeUser 
    counter = counter + 1 
    firstName = entry.GetExchangeUser.firstName 
    lastName = entry.getExchangeUser.lastName 
    sh.Cells(counter, 1).value = firstName 
    sh.Cells(counter, 2).value = lastName 
    sh.Cells(counter, 3).value = userNameBuilder(firstName, lastName) 
Next 

這裏是代碼抱怨我userNameBuilder功能時,我得到一個錯誤。

當我註釋掉「sh.Cells(counter,3).value = userNameBuilder(firstName,lastName)」時,代碼運行正常,只是不會生成用戶名。

用戶名是姓氏的前5個字母加上名字的第一個字母。如果姓氏太短,則從頭開始填充名字,直到用戶名長度爲6個字符。的

Public Function userNameBuilder(ByVal firstName As String, ByVal lastName As String) As String 
    Dim newLastName As String 
    Dim newUserName As String 
    If (lastName >= 5) Then 
     newLastName = Left(lastName, Len(lastName) - 5) 
     userNameBuilder = (newLastName & Left(firstName, 1)) 
    ElseIf (lastName < 5 && lastName > 0) Then 
     userNameBuilder = lastName & Left(firstName, 5 - (Len(lastName))) 
    Else 
     userNameBuilder = vbNullString 
    End If 
End Function 
+0

這可能並不涉及您的問題,但_「前5個字母姓氏「_將是'newLastName = Left(lastName,5)' – user3598756

+0

哦,是的,這是正確的 –

回答

0

代替

If (lastName >= 5) Then 

必須使用

If (Len(lastName) >= 5) Then 

和喜歡

Public Function userNameBuilder(ByVal firstName As String, ByVal lastName As String) As String 
    Dim newLastName As String 
    Dim newUserName As String 
    If (Len(lastName) >= 5) Then 
     newLastName = Left(lastName, 5) 
     userNameBuilder = (newLastName & Left(firstName, 1)) 
    ElseIf (Len(lastName) < 5 && Len(lastName) > 0) Then 
     userNameBuilder = lastName & Left(firstName, 5 - (Len(lastName))) 
    Else 
     userNameBuilder = vbNullString 
    End If 
End Function