[英]What's wrong with my VBA code (I'm getting runtime error 9)
我環顧四周,發現“運行時錯誤 9 下標超出范圍”錯誤通常與數組有關。 但是,我不確定如何解釋我找到的最適合我的代碼的答案。
我編寫了一個簡單的函數,用於從字段中提取名字和姓氏,然后我發現該字段中有一些 Null,並試圖通過從 String 更改為 Variant 聲明來進行補償。
我已經用類似的代碼讓它工作而沒有錯誤......但不是這個代碼。
我的代碼如下:
Function FLastName(ByVal lnIn As Variant) As Variant
Dim astrFullName() As String
If IsNull(lnIn) Then
FLastName = Null
Else
ReDim astrFullName(2) 'This is a new concept to me... not sure if I really need this
astrFullName = Split(lnIn, ",")
FLastName = astrFullName(0)
End If
End Function
預先感謝您的見解和幫助。
編輯:我發現問題在於數組不喜歡某些名稱字段中的 Null 值......我認為以下行可以解決這個問題:
If IsNull(lnIn) Then
FLastName = Null
但顯然我錯了。
任何人都對我迄今為止發現的內容有一些建議?
你真的不需要ReDim
......你甚至不必把它作為一個數組來調Dim
。
Function FLastName(ByVal lnIn As Variant) As Variant
Dim astrFullName
If IsNull(lnIn) Then
FLastName = Null
Else
astrFullName = Split(lnIn, ",")
FLastName = astrFullName(0)
End If
End Function
PS:假設 lnIn 將包含一個逗號分隔的字符串......否則你可能需要檢查。
我找到了答案!
Allen Browne(他非常棒)在他的網站上有一個“ParseWord”功能,可以處理我需要完成的工作。
可以在這里找到: http : //allenbrowne.com/func-10.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.