Split(string,",")
这样的东西,因为某些值中包含逗号(例如值:[blah blah, so blah blah])。在存在这些括号的情况下(每个包含逗号的值都有括号),我想出了一个相当复杂的方法来正确地拆分这些值,将它们放入一个数组中,然后继续执行其他任务。但是,现在我决定重新审视代码并修复精度问题。以下是一些背景信息。
可以在单个单元格中找到的示例数据:请注意:这是供应商发送给我们的数据,我们无法控制他们输入或输入方式。这是一个简单的示例,展示了数据通常在某些情况下如何提供
Available on 2 sides: Silkscreen,[full: color, covers entire face],Pad Print: One color,[heat transfer, may bleed]
数值如下:
- 可在2个方面使用:丝网印刷
- [全色,覆盖整个面部]
- 垫印:单色
- [热转印,可能会出现渗透]
我的需求:
我正在寻找一种更有效和简单的方法来正确地拆分值(同时保留具有括号的值的括号)。
我相信我已经成功创建了一种更有效和紧凑的处理不包括括号的实例的方法,使用以下代码:
新代码(正在建设中): 我遇到了一个问题,不知道如何高效而准确地拆分带有括号的单元格。
Sub Test()
Dim rngXid As Range, RegularColons As New Collection, UpchargeColons As New Collection, additionals As Range, upcharges As Range, Colon, UpchargeColon
Dim Values() As String, endRange As Long, xidMap As Object, xid As String, NumberofValues As Integer
endRange = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Set xidMap = getXidMap(ActiveSheet.Range("A2:A" & UsedRange.Rows.Count)) 'Map products for quicker navigation
Set additionals = ActiveSheet.Range("AJ:AK"): Set upcharges = ActiveSheet.Range("CS:CT")
Set RegularColons = FindAllMatches(additionals, ":") 'This returns all instances/cells that contain a colon in the specified columns
If Not RegularColons Is Nothing Then
For Each Colon In RegularColons
xid = ActiveSheet.Range("A" & Colon.Row).Value
If InStr(1, Colon.Value, "[") = 0 Then 'If no brackets then simply split
Values = Split(Trim(Colon.Value), ",")
Else
'This is where I'm at a lose for a more effective method
'-----------Populate Values array with Colon.Value while watching out for brackets--------
End If
Set rngXid = xidMap(xid).EntireRow.Columns(upcharges) 'set to this specific product
For ColorLocation = LBound(Values) To UBound(Values) 'cycle through each value in Values array
If Not InStr(1, Values(ColorLocation), ":") = 0 Then 'Only proceed if the value has a colon
Set UpchargeColons = FindAllMatches(rngXid, Values(ColorLocation)) 'Searching other columns for this value
If Not UpchargeColons Is Nothing Then
For Each UpchargeColon In UpchargeColons 'If found in other columns proceed to replace colon
UpchargeColon.Value = Replace(UpchargeColon.Value, ":", " ")
Log UpchargeColon.Range, "Removed Colon from Additional Color/Location Upcharge", "Corrected" 'This is a custom sub of mine to record the change
Next UpchargeColon
End If
Values(ColorLocation) = Replace(Values(ColorLocation), ":", " ")
End If
Next ColorLocation
Log Colon.Range, "Removed Colon(s) from Additional Color/Location Value(s)", "Corrected"
Next Colon
End If
End Sub
我一直在浏览可能的方法来完成这个任务,其中一个最突出的方法是正则表达式(Regex),虽然我之前听说过,但实际上没有任何经验。因此,我尝试阅读了一些网站(如这里和当然是msdn文档)中关于它的相关知识。我在学习这种方法时的观察/思考如下:
- 这绝对是非常复杂和压倒性的。它甚至让我不敢想象自己会不会蜷缩在角落里,假装胎位,哭泣不已。
- 我似乎找不到任何可以将此函数与适当拆分字符串的需求相结合的方法,至少我所看到的。但是,这可能只是因为我被所有看起来都是随意符号序列淹没了。
所以,我的问题是:
在包含括号的单元格中,最有效的准确拆分值的方法是什么?