2017-07-30 25 views
2

我的宏在所有打開的工作簿中搜索活動單元格值(例如98%)。但是,它只能找到值0.98而不是其他單元格中的值98%。爲什麼?VBA查找函數忽略百分比 - >只發現小數

這裏是我的宏:

Sub FindIt2() 
Dim wSheet As Worksheet 
Dim wBook As Workbook 
Dim rFound As Range 
Dim firstAddress As String 
lookfor = Selection.Value 

On Error Resume Next 
For Each wBook In Application.Workbooks 
    For Each wSheet In wBook.Worksheets 

     Set rFound = wSheet.Cells.Find(What:=lookfor, After:=wSheet.Cells(1, 1), _ 
     LookAt:=xlWhole, SearchOrder:=xlByRows, _ 
     SearchDirection:=xlNext, MatchCase:=False) 

     If Not rFound Is Nothing Then 

      firstAddress = rFound.Address 

      Do 

       Application.Goto rFound, True 

       MsgBox "The Search String has been found these locations: " 

       Set rFound = wSheet.Cells.FindNext(rFound) 

      Loop While Not rFound Is Nothing And rFound.Address <> firstAddress 

     End If 

    Next wSheet 

Next wBook 
On Error GoTo 0 

任何人有一個想法如何解決這個問題?謝謝!

編輯:我希望它找到這兩個98%和0.98

+0

你永遠不會定義你的搜索值所在的變量。因此,如果我沒有記錯,它將按定義成爲一個整數。 – Luuklag

+0

是的,你沒錯,我沒有定義它。但是,它似乎並沒有成爲一個整數,因爲我發現0.98。 什麼是適當的定義?我使用宏的許多不同類型的值.. – Lennart

+0

我認爲最好將工作表中的值轉換爲所有分數或所有百分比。否則,你最終會檢查兩個變量。 – Luuklag

回答

0

有時98%是單元格的值。即當你在單元格中輸入98%時。 Excel會將其視爲字面上的98%。在其他情況下,單元格值爲.98或.98231,並顯示98%。最有可能的是,您想要查找兩位有效數字的搜索結果,以便在值爲.98321時找到.98。

我會嘗試尋找兩者。

的cell.text和圓(cell.value,2)

How to round up with excel VBA round()?

本文介紹如何使用圓形功能在Excel VBA

+0

謝謝,不幸的是結果並不是我正在尋找的(我的問題可能不清楚)。 我想找到兩個:0.98和98%..與您的解決方案,宏只有98%,如果活動單元格值爲98%。 – Lennart

+0

我希望能解釋你所看到的。 –

0

實際上,Find與各種缺失值格式(不僅是百分比),即使數值與源相同(參數What函數Find)。 在下列各種條件下,Find只能找到其內容爲0123的單元格,帶有常規或數字(2位十進制數字)格式。

我的嘗試:

  1. 使用lookfor = Selection.Value。更改Selection指向的(源)單元格的數字格式。如果Selection的格式爲百分比,數字(帶有任何十進制數字)或常規,則無關緊要。 Find只能找到帶有0.98的單元格,而不能找到帶有0.980的單元格。使用lookfor = Selection.Text。更改Selection指向的(源)單元格的數字格式。 Find只能找到與查看的號碼完全相同的單元格。

奇怪,因爲它可能是,這需要一個解決辦法,因爲Find不會在同一時間發現兩者0.9898%。 一種選擇是使用統一格式的一個或多個幫助列,並在這些列上執行find

0

FIND不起作用時,一種解決方案是循環遍歷單元格。如果你有大量的單元格,這可能會很慢,所以將要搜索的範圍讀入變體陣列會使速度提高十倍甚至更多。

但這裏有一個循環的想法,可以讓你開始。注意我使用了value2屬性。爲什麼請參閱Charles Williams Answer

首先運行Setup宏,然後findValuePercent,看看事情是如何工作的。然後您可以根據您的具體要求進行調整。

Option Explicit 

Sub Setup() 
    Dim WS As Worksheet 
Set WS = Worksheets("sheet1") 
With WS 
    .Cells(1, 1).Value = "98%" 
    .Cells(2, 1).Value = 0.98 

    Debug.Print .Cells(1, 1).Value, .Cells(1, 1).Text ' --> 0.98 98% 
    Debug.Print .Cells(2, 1).Value, .Cells(2, 1).Text ' --> 0.98 0.98 
End With 
End Sub 

Sub findValuePercent() 
    Dim WS As Worksheet 
    Dim R As Range 
    Dim C As Range 
    Dim S As String 
    Const dWhat As Double = 0.98 

Set WS = Worksheets("sheet1") 
Set R = WS.UsedRange 

For Each C In R 
    If C.Value2 = dWhat Then 
     S = S & vbLf & C.Address & vbTab & C.Text 
    End If 
Next C 

MsgBox "Matches in" & S 

End Sub