从单元格数组中提取文本

时间:2018-01-08 09:44:56

标签: excel excel-vba excel-formula vba

我一直试图从单元格中提取特定数据,以便在“返回/输入”中对其进行排列。分开的值。我确实使用excel公式取得了成功,但需要你的帮助才能让它变得更好。我相信Excel VBA在这里会很棒。为了让你清楚,我正在使用以下链接分享一个示例excel文件。它显示了我的尝试。它还解释了共享excel文件中的数据。

http://www.filedropper.com/book1_12
点击链接,然后点击"下载此文件"

2 个答案:

答案 0 :(得分:0)

以下代码应该可以满足您的需求:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'change the name of the sheet above to the Sheet you are using
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row on Column A
For x = 1 To LastRow 'loop from row 1 to last
    For i = 1 To Len(ws.Cells(x, 1).Value) 'check length of characters in cell
        If ws.Cells(x, 1).Characters(i, 1).Font.FontStyle = "Bold" Then 'check if content is bold
            ValueToCopy = Mid(ws.Cells(x, 1), i, 1) 'get the bold character
            ws.Cells(x, 2).Value = ws.Cells(x, 2).Value & ValueToCopy 'place the character on Column B
        End If
    Next i
Next x
End Sub

答案 1 :(得分:0)

现在使用示例文件,VBA解决方案最简单。

  • 为了速度,我们在vba数组中执行“工作”而不是多次读/写工作表
  • 我们也使用完全限定的变量;良好做法,增加未来维护的灵活性
  • 读入要处理的范围
  • 将逗号添加到第一行
  • 拆分换行符上的每个条目
  • 构造结果字符串,测试以逗号
  • 开头的行
  • 将结果字符串写入vba“results”数组。
  • 将结果数组写回工作表
    • 您可能需要在代码中添加一些结果格式。
Option Explicit
Sub ExtrCountries()
    Dim wsSrc As Worksheet, rRes As Range
    Dim vSrc As Variant, vRes As Variant
    Dim I As Long
    Dim V As Variant, W As Variant
    Dim S As String


Set wsSrc = Worksheets("Sheet1")
With wsSrc
    vSrc = .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(xlUp))
    Set rRes = .Cells(2, 2)
End With

ReDim vRes(1 To UBound(vSrc, 1), 1 To UBound(vSrc, 2))

For I = 1 To UBound(vSrc, 1)
    V = Split("," & vSrc(I, 1), vbLf)
    S = ""
    For Each W In V
        If Left(W, 1) = "," Then
            S = S & vbLf & Mid(W, 2)
        End If
    Next W
    vRes(I, 1) = Mid(S, 2)
Next I

Set rRes = rRes.Resize(UBound(vRes, 1), UBound(vRes, 2))
With rRes
    .EntireColumn.ClearContents
    .Rows(1) = "DESIRED"
    .Value = vRes
'Can set some formatting options if desired
End With
End Sub