【发布时间】:2020-05-15 10:00:40
【问题描述】:
我在这里有这段代码,它设置了整个文档内容的范围,并在该范围内搜索文本 =“cenę brutto w kwocie” - 我希望它在那里。 该代码的目的是从word文档中查找并提取公寓价格并将其写入excel单元格。
我的问题与第 11 行代码 endPos = InStr(startPos, rng, ",00zł") 有关:如何将“,00zł”更改为“[0-9]{3},[0-9]{2}zł”?
我知道这些通配符可以与range.find 方法一起使用,但是这些通配符可以传递给InStr 函数吗?这些字符串“cenę brutto w kwocie”和“,00zł”在很长的word文档中非常接近。它们用于将rng 范围从最初的整个文档缩小到可以找到和检索公寓价格的非常小的范围。我需要更改它,因为有时公寓价格中包含货币小数。
'Assigning object variables and values
Set wordApp = GetObject(, "Word.Application")
Set excelApp = GetObject(, "Excel.Application")
Set wordDoc = wordApp.ActiveDocument
Set mySheet = Application.ActiveWorkbook.ActiveSheet
Set rng = wordApp.ActiveDocument.Content
Set scndRng = ActiveSheet.Range("A10:J40").Find("cena", , xlValues)
textToFind1 = "KRS 0000609737, REGON 364061169, NIP 951-24-09-783,"
textToFind2 = "- ad."
textToFind3 = "Tożsamość stawających"
textToFind4 = "PESEL"
TextToFind5 = "cenę brutto w kwocie łącznej"
textToFind6 = "cenę brutto w kwocie "
Set rng = wordApp.ActiveDocument.Content 'this command without "set" will destroy the document's formating;
With rng.Find
.Text = textToFind6 '="cenę brutto w kwocie "
.MatchWildcards = False
.MatchCase = False
.Forward = True
.Execute
If .Found = True Then
Set rng = wordApp.ActiveDocument.Content
startPos = InStr(1, rng, textToFind6) 'we're looking 4 "cenę brutto w kwocie"
endPos = InStr(startPos, rng, ",00zł") 'here we get 47380, we're looking 4 ",00zł"
startPos = startPos + Len(textToFind6) ' + 21 characters 'now start position is reassigned at 47331.
Debug.Print Replace(Mid(rng, startPos, endPos - startPos), ".", "")
price = Replace(Mid(rng, startPos, endPos - startPos), ".", "")
price = Trim(price)
Debug.Print price
End If
End With
Debug.Print scndRng.Address
scndRng.Offset(0, 1) = price
以前所有公寓价格都四舍五入为整数,因此找到“,00zł”并将其多头头寸传递给endPos 变量。
如何将 "[0-9]{3},[0-9]{2}zł" 放入 InStr 或任何其他将 long 值传递到 endPos 变量的函数中。
【问题讨论】:
-
检查这个:How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops。您可以使用正则表达式,但不能在
InStr中使用。无论如何,RegEx 将完全取代InStr。
标签: excel vba ms-word wildcard