如何删除使用数组元素添加值的空格?

时间:2012-12-29 19:52:24

标签: excel-vba vbscript vba excel

我遇到了Array值的主要问题,这些值在添加到数组时会添加空格。那么有没有办法删除这些空格意味着在单行语句中使用Trim,然后再将它们用于进一步处理,否则我需要在每次计算中使用Trim。那么在code

中一次删除这些空格的任何更快的过程
Dim VMHArray
VMHArray = Array("VMH All Fields Review - Add Supplier  Emergency", _
                 "VMH All Fields Review  (Req. Provides Supplier Details) - Update/Enable Supplier", _
                 "VMH Triggered Final Sourcing Review - Add Address_Direct", _
                 "Activate / Create supplier in business system - Add Address", _
                 "Activate / Create supplier in Business System - Add Supplier")

3 个答案:

答案 0 :(得分:3)

在插入数组时修剪值。或者,或者,循环遍历数组,修剪每个元素并将修剪后的元素重新插入到数组中。

答案 1 :(得分:2)

初始化后无法清理阵列,如下所示:

Sub test()
   Dim a(2) As String
   a(0) = "t1"
   a(1) = "t2  "
    a(2) = "test3 "
    Dim i As Integer

    Dim trimmed As Variant

    trimmed = TrimArray(a)

     For i = 0 To UBound(trimmed)
         Debug.Print trimmed(i) + "|"
     Next

End Sub

Function TrimArray(ByRef a() As String) As Variant
    For i = 0 To UBound(a)
     a(i) = Trim(a(i))
    Next

    TrimArray = a
End Function

答案 2 :(得分:1)

我的VBE不接受数组中的350个条目。

但是,对于VBA,下面的代码使用简化集:

Sub main()

Dim VMHArray As Variant

VMHArray = Array("VMH All Fields Review - Add Supplier  Emergency", _
"VMH All Fields Review (Req. Provides Supplier Details) - Update/Enable Supplier", _
"VMH Triggered Final Sourcing Review - Add Address_Direct", _
"Activate - / Create supplier in business system - Add Address", _
"Activate /Create supplier in Business System - Add Supplier", _
"Activate / Create supplier in Business System -Add Supplier Emergency")

VMHArray = TrimArrayElements(VMHArray)

End Sub

Function TrimArrayElements(InputArray As Variant) As Variant

  Dim arr_element As Variant

  For Each arr_element In InputArray
    arr_element = Trim(arr_element)
  Next

End Function