我正在使用MS Word从Excel工作簿中提取数据:
Sub Birthyard()
Dim xlapp As Object
Dim xlbook As Object
Dim xlsheet As Object
Dim SWORD As Range
Set SWORD = Selection.Paragraphs(1).Range
SWORD.MoveEnd wdCharacter, -1
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If Err Then
bstartApp = True
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
With xlapp
Set xlbook = .Workbooks.Open("C:\users\ibnea\Desktop\list.xlsm")
Set RANG = xlbook.Worksheets("Sheet4").Range("A:B").Find(SWORD)
If RANG Is Nothing Then
MsgBox "Nothing Found in Sheet4 Range(A:B)"
Else
If RANG.Column = "2" Then
COMPANY = RANG.Offset(0, -1).Value
TICKER = RANG.Value
MsgBox COMPANY & TICKER
Else
COMPANY = RANG.Value
TICKER = RANG.Offset(0, 1).Value
MsgBox COMPANY & TICKER
End If
End If
End With
If bstartApp = True Then
xlapp.Quit
End If
Set xlapp = Nothing
Set xlbook = Nothing
Set xlsheet = Nothing
End Sub
上面的代码打开一个Excel工作簿,并从前两列中查找给定的单词。问题在于当找到的文字是单词的一部分时。
例如,如果搜索词/条件包含一个小字符串,例如“ be”或“ sp”,那么我会得到一些错误的结果。我需要该功能停止在单词中寻找并从整体上看单词以进行匹配。
我发现可以通过添加trim功能来完成,而regex可以完成这项工作。我不知道如何处理这些功能。
答案 0 :(得分:3)
循环遍历所有发现的事件,直到您遇到带有单个单词的关键字:
以下是相关代码段:
With xlbook.Worksheets("Sheet4").Range("A:B")
Set RANG = .Find(what:=SWORD, lookat:=xlPart, LookIn:=xlValues)
If Not RANG Is Nothing Then
Dim firstAddress As String
firstAddress = RANG.Address
Do
If Not IsError(Application.Match(SWORD, Split(RANG, " "), 0)) Then
MsgBox "found " & SWORD & " in " & RANG.Address
' do what you need with RANG object
Exit Do
End If
Set RANG = .FindNext(RANG)
Loop While RANG.Address <> firstAddress
End If
End With
答案 1 :(得分:0)
搜索(Find
)是按行完成的,即A1,B1,A2,B2,A3,B3 ...如果要按列完成,请将xlByRows
更改为{{1} }(A1,A2,A3 ... B1,B2,B3 ...)。
xlByColumns
子例程在每个找到的包含单词(FindWord
)的单元中搜索整个单词(SWORD
)的出现。
SWORD