如何只替换字符串中的某些空格?

时间:2020-06-26 06:59:21

标签: vba

我为数据创建了导入功能。

有时导入字符串如下:

47588328 2020.06.25 11:42:13买0.11欧元1.12240 1.11902 0.00000
2020.06.25 14:05:04 1.11902 0.00 0.00 0.00 -35.35

有时是这样的

45881875
2020.05.25 19:53:14
buy
0.10
eurusd
1.08975
1.08999
1.09503
2020.05.26 10:49:17
1.09503
0.00
0.00
-0.48
51.14

我将值分成一个数组。如果字符串由换行符分隔,则没有问题。

如果字符串用空格分隔,则无法处理。我试图用换行符代替空格。
这可以工作,但是有日期和时间部分。它们必须保持在一起,当我用换行符代替空格时,它们就不需要。

我有这个:

TextboxText = UserForm1.TextBox1.Text
TextboxText = Replace(TextboxText, " ", vbLf)

我的想法之一是构建一个遍历所有空格的循环,然后仅遍历2号和10号空格。例如,使用伪代码:

> For Each Space in TextboxText     
>     If Not space nr = 2 or space nr = 10 Then
>         replace space
>     End if 
> Next

3 个答案:

答案 0 :(得分:1)

我想说是按照您的做法将其拆分为一个数组(大概使用split(strText),然后遍历该数组以重新添加日期和时间。类似以下内容

For x = LBound(myArray) to Ubound(myArray)
    'If IsDate(myArray(x)) Then - This didn't work as would erroneously return TRUE for decimals
    If Format(Cdate(myArray(x)), "yyyy") <> "1899" Then
        MyArray(x) = MyArray(x) & " " & MyArray(x+1) 'Join it to the value after
        MyArray(x+1) = "" 'Delete the value after (time value)
    End If
Next

然后,您以后对数组所做的任何操作都只需包含例如If MyArray(x) <> ""会错过那些空值。

答案 1 :(得分:0)

这不像我最初希望的那样干净,我认为可能有更好的方法可以做到,但是它确实有效:

Function GetSplit(s As String) 
Dim x As Variant: x = Split(s, " ")
Dim r(13) As String
Dim i As Long
Dim j As Long
For i = 0 To 15
    If i = 1 Or i = 9 Then
        r(j) = x(i) & " " & x(i + 1)
        i = i + 1
    Else
        r(j) = x(i)
    End If
    j = j + 1
Next i
GetSplit = r
End Function

它只是循环遍历由“”分隔的数组,并在相同位置移动值,除非它们位于位置1或9(空间2或10),在这种情况下,它会合并并增加1的数组计数器,使用像这样:

Sub test()
Dim s As String: s = "47588328 2020.06.25 11:42:13 buy 0.11 eurusd 1.12240 1.11902 0.00000 2020.06.25 14:05:04 1.11902 0.00 0.00 0.00 -35.35"
Dim resultArray As Variant
    resultArray = GetSplit(s)
End Sub

当然,这仅在每次输入的字符串格式完全相同的情况下才有效,我希望这些日期不要动!

修改

我尝试编辑此代码以利用IsDate使其更具动态性,但是IsDate对于其中的许多字符串都返回true,例如“ 0.11”是一个日期,甚至在实际日期中返回false(可能是由于区域设置所致)

答案 2 :(得分:0)

此代码直接返回一个字符串而不会循环,但它还基于以下前提:您的日期位置永远不会改变,并且带有一个神奇的“ <dt>”占位符字符串!

Function GetSplit2(s As String) As String
Dim x As Variant: x = Split(s, " ")
    s = Replace(s, x(1) & " " & x(2), x(1) & "<dt>" & x(2))
    s = Replace(s, x(9) & " " & x(10), x(9) & "<dt>" & x(10))
    s = Replace(s, " ", vbCrLf)
    GetSplit2 = Replace(s, "<dt>", " ")
End Function

像这样使用:

Sub test()
Dim s As String: s = "47588328 2020.06.25 11:42:13 buy 0.11 eurusd 1.12240 1.11902 0.00000 2020.06.25 14:05:04 1.11902 0.00 0.00 0.00 -35.35"
MsgBox GetSplit2(s)
End Sub