我正在VBA中进行索引匹配查找,并且在使用普通数字时它可以正常工作但是当它被格式化为百分比时它不起作用,它会抛出错误。我该如何解决这个问题?
Sub TOP10() 'doesnt work on percentages
Dim rngTestArea As Range
Dim i, j As Long
Dim MyResult As String
lastRow = ThisWorkbook.Worksheets("GEODISTRIBUTION").Range("C" & Rows.Count).End(xlUp).Row
Set rngTestArea = ThisWorkbook.Worksheets("GEODISTRIBUTION").Range("K11:K" & lastRow)
j = 0
For i = 1 To 10
j = Application.WorksheetFunction.Large(rngTestArea, i)
Location = Application.WorksheetFunction.Index(Sheets("GEODISTRIBUTION").Range("C11:C" & lastRow), Application.WorksheetFunction.Match(j, rngTestArea, 0), 1)
geodis = geodis & Location & " - " & j & ","
Next i
MsgBox geodis
End Sub
答案 0 :(得分:1)
我无法复制你的确切问题...除了我无法让它运行而没有声明Location和geodis作为Variant(我也拉出了比赛以查看那里发生了什么)。 /> 在那之后,我让它以百分比运行。以下是我测试的K11:K25中的值:(我没有你的数据,所以我不得不用26结束我的最后一行进行测试。)
1 2 3 4 五 6 7 8 0.25 五 5800% 58 五 52 88
以下是我用来调试运行代码的内容:
Sub TOP10() 'doesnt work on percentages
Dim rngTestArea As Range
Dim i, j As Integer
Dim MyResult As String
Dim Location As Variant
Dim geodis As Variant
Dim match As Variant
lastRow = ThisWorkbook.Worksheets("GEODISTRIBUTION").Range("C" & Rows.Count).End(xlUp).Row
lastRow = 26
Set rngTestArea = ThisWorkbook.Worksheets("GEODISTRIBUTION").Range("K11:K" & lastRow)
j = 0
Debug.Print rngTestArea.Address
For i = 1 To 10
Debug.Print "i: " & i
j = Application.WorksheetFunction.Large(rngTestArea, i)
Debug.Print "j: " & j
match = Application.WorksheetFunction.match(j, rngTestArea, 0)
Debug.Print "match: " & match
Location = Application.WorksheetFunction.Index(Sheets("GEODISTRIBUTION").Range("C11:C" & lastRow), match, 1)
Debug.Print "Location: " & Location
geodis = geodis & Location & " - " & j & ","
Debug.Print "geodis: " & geodis
Next i
Debug.Print geodis
'MsgBox geodis
End Sub
答案 1 :(得分:0)
我将值2.24101235446119%
放在单元格K11中,将公式放在下面的单元格中:=K11-0.01
下到第111行(加上列C中的值以查找最后一行)。
此代码为位置返回1 - 我已将j
更改为double i
为long,并声明了一些缺失变量。除此之外,它是您的确切代码。
Sub TOP10() 'doesnt work on percentages
Dim rngTestArea As Range
Dim i As Long, j As Double
Dim MyResult As String
Dim lastrow As Long
Dim Location As Variant
Dim geodis As String
lastrow = ThisWorkbook.Worksheets("GEODISTRIBUTION").Range("C" & Rows.Count).End(xlUp).Row
Set rngTestArea = ThisWorkbook.Worksheets("GEODISTRIBUTION").Range("K11:K" & lastrow)
j = 0
For i = 1 To 10
j = Application.WorksheetFunction.Large(rngTestArea, i)
Location = Application.WorksheetFunction.Index(Sheets("GEODISTRIBUTION").Range("C11:C" & lastrow), Application.WorksheetFunction.Match(j, rngTestArea, 0), 1)
geodis = geodis & Location & " - " & j & ","
Next i
MsgBox geodis
End Sub