Vbscript 将 excel 中的列数据拆分为 excel 中的 2 列

Vbscript to split excel column data inexcel into 2 columns

我正在尝试拆分 excel sheet 中的数据,如下所示:

|a a    1|
|b b    2|
|c c    3|
|d d d  4|

|a a| 1|
|b b| 2|
|c c| 3|
|d d d| 4|

我观察到一种模式,如果在任何特定单元格(或行)的字符之间有多个 space,则应将它们分成单独的列。

使用查找

的 RegExp
  1. 非贪婪
  2. 的Not-\ns序列
  3. 在一个非空的空白序列之前
  4. 后跟数字

如:

Option Explicit

Function qq(s) : qq = """" & s & """" : End Function

Dim r : Set r = New RegExp
r.Pattern = "^(.+?)\s+(\d+)$"
Dim s, m
For Each s In Split("a a    1|d d d  4", "|")
    Set m = r.Execute(s)(0)
    WScript.Echo qq(m.Submatches(0)), qq(m.Submatches(1))
Next

输出:

cscript 31160562.vbs
"a a" "1"
"d d d" "4"

你可以根据space,

编写一个使用Split函数的函数

下面是您认为适合您的代码片段

    Dim arrVar
    strCelldata = Worksheets("Sheet1").Cells(1, 1)
    arrVar = Split(strCelldata, "  ")
    j = 2
    For Each arrVal In arrVar
        If Trim(arrVal) <> "" Then
            Worksheets("Sheet1").Cells(1, j) = arrVal
            j = j + 1
        End If
    Next

您可能需要再添加一个 for 循环以遍历 excel sheet 上的所有可用数据。

我会使用正则表达式将 2 个或多个连续空格的序列替换为制表符,然后使用 TextToColumns 方法将列一分为二:

Set xl = CreateObject("Excel.Application")
xl.Visible = True

Set wb = xl.Workbooks.Open("C:\path\to\your.xlsx")
Set ws = wb.Sheets(1)

Set re = New RegExp
re.Pattern = "  +"

For Each cell In ws.UsedRange
  cell.Value = re.Replace(cell.Value, vbTab)
Next

ws.UsedRange.TextToColumns