如何使用自定义模块在数字之间添加逗号

我有一个自定义模块创build一个名为“Myvlookup”的function,其function类似于VLOOKUP,但在一个单元格中输出多个数字。 这里是代码:

Function MYVLOOKUP(lookupval, lookuprange As Range, indexcol As Long) Dim r As Range Dim result As String result = "" For Each r In lookuprange If r = lookupval Then result = result & " " & r.Offset(0, indexcol - 1) End If Next r MYVLOOKUP = result End Function 

这是行得通的,但我想知道我可以改变它,所以我可以在数字之间加一个逗号。 我试图在“”之间添加它,但是在第一个数字之前创build了一个逗号,并且想知道是否有添加另一个可以摆脱第一个逗号的方法。

您可以像您所说的那样添加逗号,并在设置MYLOOKUP时添加Mid语句:

 For Each r In lookuprange If r = lookupval Then result = result & ", " & r.Offset(0, indexcol - 1) End If Next r MYVLOOKUP = Mid(result,2) 

这允许你不添加另一行代码

另一个select也是这样做的,但它更笨拙:

 For Each r In lookuprange If r = lookupval Then If result = "" Then result = r.Offset(0, indexcol -1) Else: result = result & ", " & r.Offset(0, indexcol - 1) End If Next r