excel - 使用特定关键字拆分 Excel 文件列中的语句

标签 excel vba

我有一个包含多列数据的 excel 文件。我需要从文件中选择一列,并使用单元格中的特定关键字分隔该列的每个单元格中的数据。
每个单元格的关键字相同

enter image description here

现在我想做的是,我想将每个字母与单元格分开,并给它们一个标题,如下图所示

enter image description here

最佳答案

以下 VBA 代码应该可以解决问题:

Option Explicit

Public Sub MainSub()

Dim arr As Variant
Dim srcRow As Long, destRow As Long
Dim wsSrc As Worksheet, wsDest As Worksheet

Set wsSrc = ThisWorkbook.Worksheets("Sheet1")
Set wsDest = ThisWorkbook.Worksheets.Add(Before:=wsSrc)

wsDest.Cells(1, 1).Value2 = "Letter"
wsDest.Cells(1, 2).Value2 = "Value"
destRow = 2

For srcRow = 1 To wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row
    If InStr(1, wsSrc.Cells(srcRow, 1).Value2, "half:", vbTextCompare) Then
        arr = Split(wsSrc.Cells(srcRow, 1).Value2, "half:")(0)
        arr = Split(arr, "/")
        destRow = WriteToDest(arr, "FULL", destRow, wsDest)
        arr = Split(wsSrc.Cells(srcRow, 1).Value2, "half:")(1)
        arr = Split(arr, "/")
        destRow = WriteToDest(arr, "HALF", destRow, wsDest)
    Else
        arr = Split(wsSrc.Cells(srcRow, 1).Value2, "/")
        destRow = WriteToDest(arr, "FULL", destRow, wsDest)
    End If
Next srcRow

End Sub

Private Function WriteToDest(arr As Variant, HalfOrFull As String, destRow As Long, wsDest As Worksheet) As Long

Dim element As Long

For element = LBound(arr) To UBound(arr)
    If Trim(arr(element)) <> vbNullString Then
        wsDest.Cells(destRow, 1).Value2 = UCase(Trim(arr(element)))
        wsDest.Cells(destRow, 2).Value2 = "FULL"
        destRow = destRow + 1
    End If
Next element

WriteToDest = destRow

End Function

只需将其全部复制到一个空模块中并调整Set wsSrc = ThisWorkbook.Worksheets("Sheet1")中的工作表名称即可到数据所在工作表的实际名称。

然后,上面的代码将插入一个新工作表并按照上面帖子中的描述处理/输出数据。

关于excel - 使用特定关键字拆分 Excel 文件列中的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203454/

相关文章:

java - 在 Java Poi (Excel) 中更改单元格格式(长度?)

vba - 自定义 VBA 函数返回 #NAME?

excel - 为什么 Excel 调用的 UDF 次数超出了要求?

excel - EntireRow.Delete 性能问题

excel - VBA从模块更改实例变量(excel)

excel - 单击任务 Pane 内容内部并立即滚动工作表会导致 Excel 无响应

python - 如何使用 xlsxwriter 格式化索引列?

excel - 硬编码一个简单的 4X3 数组

vba - 将超链接放入MessageBox

oracle - 由于系统错误 193 : (Oracle in instant client_11_2, C :\. ..\SQORA32.dll),无法加载 VBA ODBC Oracle 指定的驱动程序