我目前正在从工作表1中分割包含3个元素(a/b/c)的字符串,并将每个部分粘贴在工作表2上的不同列中。这是由一个循环完成的。
但是,如果字符串只有2元素,那么上面的"c“是空的,我得到了运行时错误9:”超出范围的索引“。
字符串可以而且有时只包含1或2个元素,而不是所有的3个。有什么方法可以避免这个错误吗?
我的研究导致我尝试了Len(Trim()) = vbnullstring和Len() =0,但是没有什么效果。
任何帮助都将不胜感激!
For Each IDrow In wsInput.Range(IDcolLetter & "2:" & IDcolLetter & lastRow)
'Fourthly, get the respective row-number for each skill
IDrowNumber = Split(IDrow.Address, "$")(2)
'Fifthly, split the strings in 3 parts
Dim myElements() As String
myElements = Split(wsInput.Range(IDcolLetter & IDrowNumber).value, "\")
'Sixthly, for every skill of that supplier, copy the ID in A, CG in B, Category in C and Product in D
NextRow = ws4.Range("A" & Rows.Count).End(xlUp).row + 1
If Len(myElements(2)) = 0 Then <<<<<<<<<<<<<<<<<<<<<ERROR HERE<<<<<<<<<<<<<<<<<<<<<<<
wsInput.Range(IDcolLetter & "1").Copy Destination:=ws4.Range("A" & NextRow) 'ID
ws4.Range("B" & NextRow) = myElements(0) 'Commodity Group
ws4.Range("C" & NextRow) = myElements(1) 'Category
Else
wsInput.Range(IDcolLetter & "1").Copy Destination:=ws4.Range("A" & NextRow) 'ID
ws4.Range("B" & NextRow) = myElements(0) 'Commodity Group
ws4.Range("C" & NextRow) = myElements(1) 'Category
ws4.Range("D" & NextRow) = myElements(2) 'Product
End If
Next IDrow发布于 2016-09-08 07:06:55
这既是一个答案,也是一个代码评审。
IDrow是一个range对象。假设IDrow.Address = "A100"
Split(IDrow.Address, "$")(2) = 100IDrow.Row = 100这两个值也是相同的。
wsInput.Range(IDcolLetter & IDrowNumber).valueIDrow.value您最好通过调整范围以匹配元素的数目来分配myElements的值。这更易读,因为它清除了许多重复的代码。
ws4.Range("B" & NextRow).Resize(1, UBound(myElements) + 1) = myElements
这两行做的事情是一样的。我试图推广后一种模式,因为我觉得它更干净,更容易阅读。
For Each IDrow In wsInput.Range(IDcolLetter & "2:" & IDcolLetter & lastRow)For Each IDrow In wsInput.Columns(IDcolLetter).Rows("2:" & lastRow)Dim myElements() As String
With wsInput
For Each IDrow In wsInput.Columns(IDcolLetter).Rows("2:" & lastRow)
'Fifthly, split the strings in 3 parts
myElements = Split(IDrow.Value, "\")
'Sixthly, for every skill of that supplier, copy the ID in A, CG in B, Category in C and Product in D
NextRow = ws4.Range("A" & Rows.Count).End(xlUp).Row + 1
.Range(IDcolLetter & "1").Copy Destination:=ws4.Range("A" & NextRow)
ws4.Range("B" & NextRow).Resize(1, UBound(myElements) + 1) = myElements
Next IDrow
End With发布于 2016-09-08 06:29:45
您可以使用UBound(myElements)获取myElements数组中在Split之后的元素数。
将下列代码添加到现有代码中:
'Fifthly, split the strings in 3 parts
Dim myElements() As String
myElements = Split(wsInput.Range(IDcolLetter & IDrowNumber).Value, "\")
Dim arrCount As Long
' count the upper bound limit of myElements array
arrCount = UBound(myElements)
' if there is an Element 3 (from Split function)
If arrCount >= 2 Then
' add the rest of your code here...
End If发布于 2016-09-08 06:34:48
简单地使用
ws4.Range("B" & NextRow).Resize(, UBound(myElements)).Value = myElementshttps://stackoverflow.com/questions/39383681
复制相似问题