【发布时间】:2015-06-12 12:42:09
【问题描述】:
我写了一个子程序来删除一行中的空白条目而不移动单元格,但它似乎不必要地笨重,我想就如何改进它获得一些建议。
Public Sub removeBlankEntriesFromRow(inputRow As Range, pasteLocation As String)
'Removes blank entries from inputRow and pastes the result into a row starting at cell pasteLocation
Dim oldArray, newArray, tempArray
Dim j As Integer
Dim i As Integer
'dump range into temp array
tempArray = inputRow.Value
'redim the 1d array
ReDim oldArray(1 To UBound(tempArray, 2))
'convert from 2d to 1d
For i = 1 To UBound(oldArray, 1)
oldArray(i) = tempArray(1, i)
Next
'redim the newArray
ReDim newArray(LBound(oldArray) To UBound(oldArray))
'for each not blank in oldarray, fill into newArray
For i = LBound(oldArray) To UBound(oldArray)
If oldArray(i) <> "" Then
j = j + 1
newArray(j) = oldArray(i)
End If
Next
'Catch Error
If j <> 0 Then
'redim the newarray to the correct size.
ReDim Preserve newArray(LBound(oldArray) To j)
'clear the old row
inputRow.ClearContents
'paste the array into a row starting at pasteLocation
Range(pasteLocation).Resize(1, j - LBound(newArray) + 1) = (newArray)
End If
End Sub
【问题讨论】:
-
此类问题您可能需要考虑code review。
-
@hexereisoftware 我really hate that attitude toward vba development。这段代码肯定有改进的余地。专业人士应该这样做。我赞赏这个人认识到它可以改进并寻求帮助。
-
@RubberDuck 我自己开发 VBA,我的评论不应该向 VBA 开发传递任何负面信息。我只是指出,代码中没有错误,并且正如您所提到的,它更好地放在代码审查中,因为在这里我希望出现更多问题,这些问题根本不工作或有错误。所以从这个角度来看,代码很好,它肯定可以优化——但不是在这里:)
-
对于@hexereisoftware 的误解,我深表歉意。很高兴知道我们意见一致。