我是一名图形艺术家,刚接触 Excel 和 VBA,但我试图用它来处理 excel 中的大量数据,以便在 Illustrator 中用作可变数据。
如果我想将带有产品名称的单元格转换为“Budwieser、Bud Light 和 Bud Black Crown”等标志的缩写形式,格式为“Budweiser_BL_BBC”
我编写了一个我认为可以完成任务的函数,但它返回 #VALUE
!
编辑
解释逻辑:我的想法是获取字符串,将其拆分为“&”,然后将结果数组的第一个位置拆分为“,”,然后将“&”之后的内容添加到第二个数组的末尾 -这个数组 sProd 将产品分隔到数组的不同位置。
然后循环遍历该数组并在空间处拆分每个产品,从而创建一个锯齿状数组。
然后再次循环遍历该数组,创建一个字符串,该字符串仅包含每个产品中每个单词的第一个字母,并用下划线分隔产品。异常(exception)是第一个产品的第一个单词被拼写并以正确的大小写设置。 (刚刚在我的逻辑中看到一个错误并添加了第一个单词异常的代码)。
编辑#2
该函数应返回一个字符串,其中原始字符串的第一个单词以正确的大小写设置,所有其他单词缩写为它们的第一个字母,乘积用下划线分隔。因此,“Budweiser, Bud Light & Bud Light Lime”返回“Budweiser_BL_BLL”,“All Coke & Dr Pepper Products”返回“AllC_DPP”,“Gatorade”返回“Gatorade”。
这是我第一次使用 Excel 和 VBA。
Function Abbrev(p As String) As String
Dim sAmpersand() As Variant
Dim sProd() As Variant
sAmpersand = Split(p, " & ")
sProd = Split(sAmpersand(0), ", ")
sProd(UBound(sProd)) = sAmpersand(1)
Dim ProductCount As Integer
Dim ProductEnd As Integer
ProductEnd = UBound(sProd) - 1
For ProductCount = 0 To ProductEnd
sProd(ProductCount) = Split(sProd(ProductCount), " ")
ProductCount = ProductCount + 1
Next ProductCount
Dim WordCount As Integer
Dim WordEnd As Integer
WordEnd = UBound(sProd(ProductCount)) - 1
Abbrev = StrConv(sProd(0)(0), vbProperCase)
For ProductCount = 0 To ProductEnd
For WordCount = 0 To WordEnd
If ProductCount = 0 Then
WordCount = 1
End If
Abbrev = Abbrev & Left(sProd(ProductCount)(WordCount), 1)
WordCount = WordCount + 1
Next WordCount
If ProductCount + 1 < ProductEnd Then
Abbrev = Abbrev & "_"
End If
ProductCount = ProductCount + 1
Next ProductCount
End Function
最佳答案
工作代码:
Function Abbrev(p As String) As String
Dim res As String, w1, w2
res = Split(Split(p, ",")(0), " ")(0)
If res = Split(p, ",")(0) Then res = res & "_"
For Each w1 In Split(Mid(Replace(p, " &", ","), Len(res) + 1), ",")
For Each w2 In Split(w1, " ")
res = res & Left(w2, 1)
Next w2
res = res & "_"
Next w1
Abbrev = IIf(Right(res, 1) <> "_", res, Left(res, Len(res) - 1))
End Function
关于vba - 字符串到缩写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22536826/