excel vba宏 - 从where子句中提取值

时间:2011-09-22 13:26:59

标签: excel-vba vba excel

在excel表'输入'的columnA中,我有以下内容(每行都在表格的新行上):

    update my_table
    set time = sysdate,
    randfield1 = 'FAKE',
    randfield5 = 'ME',
    the_field8 = 'test'
    where my_key = '84'
    ;
    update my_table
    set time4 = sysdate,
    randfield7 = 'FAeKE',
    randfield3 = 'MyE',
    the_field9 = 'test'
    where my_key = '37';

我正在尝试创建一个新的工作表'输出',它只包含columnA中的以下值,但我不知道如何在 - >之后提取引号之间的位。 my_key:

84
37

有些注意事项:能够在工作表'input'的单元格B1中指定字段名称会很棒,在本例中它将是my_key。

以前,我一直在使用过滤器列手动执行此操作,其中文本包含'where'然后在等于之后剥离所有内容然后在单引号上执行查找/替换; s。有没有人能够通过单击按钮宏来实现这一目标?

2 个答案:

答案 0 :(得分:1)

虽然使用Filtering或Find非常有效,但我不认为你会看到使用variant数组来保存输入表的所有值,使用InputB1中的字段名对正则表达式进行测试,而不是匹配的数字部分被转储到A列输出。

Sub VarExample()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim X
Dim Y
Dim lngRow As Long
Dim objRegex
Dim objRegexMC
Set ws1 = ActiveWorkbook.Sheets("Input")
Set ws2 = ActiveWorkbook.Sheets("Output")
Set objRegex = CreateObject("vbscript.regexp")
objRegex.Pattern = ".+where.+" & ws1.[b1] & ".+\'(\d+)\'.*"
 X = ws1.Range(ws1.[a1], ws1.Cells(Rows.Count, "A").End(xlUp)).Value2
ReDim Y(1 To UBound(X, 1), 1 To UBound(X, 2))
For lngRow = 1 To UBound(X, 1)
    If objRegex.test(X(lngRow, 1)) Then
    Set objRegexMC = objRegex.Execute(X(lngRow, 1))
        lngCnt = lngCnt + 1
       Y(lngCnt, 1) = objRegexMC(0).submatches(0)
    End If
Next
ws2.Columns("A").ClearContents
ws2.[a1].Resize(UBound(Y, 1), 1).Value2 = Y
End Sub

答案 1 :(得分:1)

一个简单的解决方案,但绝对不是一个好的解决方案可能是这样的:

Sub getWhere()

    Dim sRow as Integer
    Dim oRow as Integer
    Dim curSheet as Worksheet
    Dim oSheet as Worksheet

    dim words() as String

    Set curSheet = ThisWorkbook.Sheets("Input")
    Set oSheet = ThisWorkbook.Sheets("Output")


    sRow = 1
    oRow = 1
    Do while curSheet.Range("A" & sRow).Value <> ""
       If Instr(lcase(curSheet.Range("A" & sRow).Value), "where") > 0 Then
             words = Split(curSheet.Range("A" & sRow).Value, " ")
             oSheet.Range("B" & oRow).Value = words(1)
             oSheet.Range("C" & oRow).Value = getNumeric(words(3))
             oRow = oRow + 1
       End If

       sRow = sRow +1
    Loop
End Sub

    Function getNumeric(ByVal num As String) As Long
       Dim i As Integer
       Dim res As String

       For i = 1 To Len(num)
          If Asc(Mid(num, i, 1)) >= 48 And Asc(Mid(num, i, 1)) <= 57 Then res = res & Mid(num, i, 1)
       Next
       getNumeric = CLng(res)

    End Function