在週五的一些好的建議,這幫助我修復我的VBA代碼之後,我想我會試着用一個類似的用戶定義的函數。這裏的想法是採取值的列表和(可選的)表引用(例如「t」)以最終字符串結尾: t.value1 + t.value2 + t.value3Excel UDF - 獲得價值!錯誤,不知道爲什麼
它編譯好我檢查了它的錯別字和錯誤的名字(儘管可能我仍然錯過了一些東西)。當我嘗試在工作表中使用它時,我收到了「VALUE!」錯誤。下面的代碼保存在Excel中的VBA編輯器中的模塊中。
在此先感謝您的任何建議。
(附註:原諒我「VBA傻瓜」式的意見 - 這是因爲我上午一個VBA假!)
'Here we'll create the formula's structure - these are the bits the worksheet user will choose:
Function ConcatenateToAdd(ConcatenateRange as Range, Optional TableReference as String = "") As Variant 'the default value for TableReference will be ""
'And here are our other building blocks that we'll use behind the scenes:
Dim i As Long
Dim strResult1 As String 'this will be everything up to the last value
Dim strResult2 As String 'this will add the last value on to the string produced as strResult1
Dim Separator1 As String
Dim Separator2 As String
Separator1 = "." 'this will slip between the table reference and the field name
Separator2 = " + " 'this will go after each field name, except the last.
'Just in case - let's make a back-up plan
On Error GoTo ErrHandler
'OK - let's go!
'First, let's string together every value but the last one:
For i = 1 To ConcatenateRange.Count - 1
strResult1 = strResult1 & TableReference & Separator1 & ConcatenateRange.Cells(i).Value & Separator2
Next i
'Lovely! Now let's just add on the last one - this one won't have a + on the end.
For i = ConcatenateRange.Count - 0 To ConcatenateRange.Count + 0 'I'm sure this is not the most elegant way to phrase this...
strResult2 = strResult1 & TableReference & Separator1 & ConcatenateRange.Cells(i).Value
Next I
'The next bit tells Excel what the final result of the formula should be, in the worksheet:
ConcatenateToAdd = strResult2
'And this is what the error handler does - it will just make Excel shout "ERROR!" at you. Let's hope it doesn't need to.
ErrHandler:
ConcatenateToAdd = CVErr(xlErrValue)
'And that's all!
End Function
意識到我錯過了一些代碼,但已經嘗試過,並沒有區別。缺少的位是:ConcatenateToAdd = strResult2。我現在已經將它添加到了我的問題中 - 只是想解釋一下任何人已經準備好了我最初發布的代碼。 –