我希望有人可以帮助解决我收到的错误吗?
我正在尝试使用大量文本在单元格中查找值。我正在尝试在单元格中找到文本"TOTAL DDD AMOUNT"
,然后返回值
(注意 - Range("P1458")
是一个示例单元格,我知道该值存在且应该返回一个值。)
Dim ValDDDRng As Range
Set ValDDDRng = Worksheets("DATA2").Range("P1458")
Dim ValDDD As Variant
If Not IsError(Mid(ValDDDRng, InStr(1, ValDDDRng, "TOTAL DDD AMOUNT", _
vbTextCompare) + 17, (InStr(1, ValDDDRng, ",", vbTextCompare)) _
- (InStr(1, ValDDDRng, "TOTAL DDD AMOUNT", vbTextCompare)))) Then
单元格中正在查找这些值的文本示例。有时,开始可能包含其他文本,因此与金额可能在单元格中的位置不一致。我希望返回值75.33
,但首先要澄清获取值时没有错误。如果IsError
返回错误,则返回Nothing,但Else返回实际值(来自示例£75.33)
****税:58.99 GBR,总DDD金额:75.33 GBR,总费用:16.34 GBR,**蓝/绿**,文件记录准备,*****清除DDD ***** < / p>
当我运行If Not IsError示例时,我收到一个无效的过程调用或参数
答案 0 :(得分:2)
在"TOTAL DDD AMOUNT"
之后找到第一个数值的解决方案被分为两部分。
第1部分:使用Instr
函数查找单元格内"TOTAL DDD AMOUNT"
字符串的位置。
xPos = InStr(1, ValDDDRng, "TOTAL DDD AMOUNT", vbTextCompare) '<-- result is 23
第2部分:使用RegEx
对象获取第一个数字结果(采用任何十进制值格式),只查看Cell的文本,从"TOTAL DDD AMOUNT"
,使用Reg.Execute(Mid(ValDDDRng, xPos))
。
在您的示例中,Mid(ValDDDRng, xPos)
=&#34; TOTAL DDD金额:75.33 GBR,总费用:16.34 GBR,**蓝/绿**,文件记录准备,*****清除DDD * ****&#34;
<强>代码强>
Dim ValDDDRng As Range
Dim ValDDD As Variant, xPos As Long
' RegEx variables
Dim Reg As Object
Dim RegMatches As Variant, Match As Variant
Set ValDDDRng = Worksheets("DATA2").Range("P1458")
xPos = InStr(1, ValDDDRng, "TOTAL DDD AMOUNT", vbTextCompare)
Set Reg = CreateObject("VBScript.RegExp")
With Reg
.Global = True
.IgnoreCase = True
.Pattern = "(\d+)(?:\.(\d{1,2}))?" ' Match number (with decimals)
End With
Set RegMatches = Reg.Execute(Mid(ValDDDRng, xPos))
If RegMatches.Count >= 1 Then ' make sure there is at least 1 match
ValDDD = RegMatches(0) ' <-- this is the numeric value you are looking for
End If
答案 1 :(得分:2)
您的原始代码会抛出该错误,因为TOTAL DDD AMOUNT
这意味着您正在尝试将负数传递给Mid
命令。
如果将命令分成不同的阶段,则更容易看到:
Sub original()
Dim ValDDDRng As Range
Set ValDDDRng = Worksheets("DATA2").Range("P1458")
Dim ValDDD As Variant
Dim totalPos, commaPos As Integer
Dim total As String
Dim totalSearch As String
totalSearch = "TOTAL DDD AMOUNT"
totalPos = InStr(1, ValDDDRng, totalSearch, vbTextCompare)
commaPos = InStr(1, ValDDDRng, ",", vbTextCompare)
total = Mid(ValDDDRng, totalPos + 17, commaPos - totalPos) ' commaPos - totalPos is negative!
If Not IsError(total) Then
MsgBox "Total is " & total
Else
MsgBox "Is error"
End If
End Sub
以下代码段在TOTAL DDd AMOUNT
之后找到逗号,然后找到75.33 GBR
Sub improved()
Dim ValDDDRng As Range
Set ValDDDRng = Worksheets("DATA2").Range("P1458")
Dim ValDDD As Variant
Dim totalPos, commaPos As Integer
Dim total As String
Dim totalSearch As String
totalSearch = "TOTAL DDD AMOUNT"
totalPos = InStr(1, ValDDDRng, totalSearch, vbTextCompare)
commaPos = InStr(totalPos, ValDDDRng, ",", vbTextCompare) ' need to find the second comma
total = Mid(ValDDDRng, totalPos + 17, commaPos - totalPos - Len(totalSearch) - 1)
If Not IsError(total) Then
MsgBox "Total is " & total
Else
MsgBox "Is error"
End If
End Sub
所有这一切,根据Shai Rado的回答使用正则表达式是一个更简洁的解决方案,并且在涉及不同的输入文本时不那么脆弱。我只是想告诉你错误的来源以及如何重新安排代码以便于调试