在周五的一些好的建议,这帮助我修复我的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。我现在已经将它添加到了我的问题中 - 只是想解释一下任何人已经准备好了我最初发布的代码。 –