Excel VBA - 查找_或。在单词中然后将单词放在单独的字段中

时间:2014-01-22 14:49:47

标签: excel vba excel-vba find

我有一个包含每个单元格中的SQL的大型单元格列表。我想找到_.的任何单词,然后从单元格中拉出该单词并放入相邻的单元格。

2或10个字可能有_.

基本上,我尝试识别SQL中的所有[fields]并在实际的SQL旁边创建它们的列表。

提前感谢您提供的任何帮助。 Excel 2007

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题,我想:

Option Explicit
Sub PrintSQLFields()

Dim rng As Range
Dim r As Range
Dim str As String
Dim i%
Dim possibleFields As Variant
Dim substr As Variant


Set rng = Range("A1:A10")    '## MODIFY AS NEEDED, but should be a single column

For Each r In rng.Cells
    i = 0
    str = r.Value
    'replace the parentheses
    str = Replace(str, "(", " ")
    str = Replace(str, ")", " ")

    'Split by space
    possibleFields = Split(str, " ")
    For Each substr In possibleFields

        'Check if the substring contains either "_" or "."
        If StrContains(CStr(substr), "_") Or StrContains(CStr(substr), ".") Then
            'print value to next adjacent cell
            i = i + 1
            r.Offset(0, i).Value = substr
        End If
    Next
Next

End Sub

Function StrContains(str$, char$) As Boolean

    If InStr(1, str, char) Then StrContains = True

End Function