2015-03-23 2 views
2

Я написал несколько скриптов VBA для поиска диапазона дат в списке, он может найти даты, но по какой-то причине он не может соответствовать их целевому диапазону. Я тестировал целевой диапазон с помощью vlookup, который возвращает совпадение, но код .find, похоже, не работает одинаково.Excel VBA - не могу .find date string в диапазоне

Например, Sourcecolumnvalue получит дату в своем диапазоне (скажем, 01/02/2015). Значение sourcecolumn будет отражать это, но, похоже, не может найти это в целевом диапазоне, как указано в строке .find.

Я что-то не так с этим кодом?

Sub Finddates() 
Dim SourceColumnValue As String, sourcerow As String, targetrow As String 
Dim M As Long, O As Long, TargetValue As Long, actualsourcerow As Long, actualtargetrow As Long, actualtargetcolumn As Long, sourcedateposition As Long 
TargetValue = dumpsheet.Cells(rows.Count, 1).End(xlUp).row 
sourcedateposition = dumpsheet.Cells(rows.Count, 5).End(xlUp).row 

'Loop Source Column 
For F = 1 To sourcedateposition 
SourceColumnValue = dumpsheet.Cells(F, 5).Value 


    'Get Target Column Match to Source 
    Set TargetColumnRange = dumpsheet.Range("G2:G" & TargetValue).Find(What:=SourceColumnValue, _ 
                  LookIn:=xlValues, _ 
                  LookAt:=xlWhole, _ 
                  SearchOrder:=xlByRows) 
       'if a match is found 
       If Not TargetColumnRange Is Nothing Then 
        TargetColumnRange.Value = SourceColumnValue 

         For O = 1 To dumpsheet.Range("A2:A" & rows.Count).End(xlUp).row 
         Sourcename = ActiveCell(O, 1).Value 
         sourcerow = ActiveCell(O, 2).Value 
         targetrow = ActiveCell(O, 3).Value 

         actualsourcerow = CInt(sourcerow) 
         actualtargetrow = CInt(targetrow) 
         actualtargetcolumn = CInt(TargetColumn) 

         CapexTargetSheet.Activate 
         Cells(actualtargetrow, actualtargetcolumn).Value = CapexSourceSheet.Cells(actualsourcerow, F).Value 
        Next O 
       End If 
Next F 
End Sub 
+0

смог опубликовать образец файла для нас работать с Вы? – brettdj

ответ

1

мне удалось написать код используя цикл, а не используя .find, который оказался очень в соответствии с датами. Я читал в другой статье, что использование строк для дат лучше, потому что фактическое числовое значение даты сохраняется в строке. Я преобразовал исходные и целевые даты в строки, а затем сделал совпадение с использованием цикла, который работает хорошо. Но спасибо за ваш ответ, это действительно положило меня на правильный путь!

Ниже

Dim SourceColumnValue As String, sourcerow As String, targetrow As String, targetcolumnvalue As String, sourcecolumnnumber As String 
Dim M As Long, O As Long, P As Long, TargetValue As Long, actualsourcerow As Long, actualtargetrow As Long, actualtargetcolumn As Long, sourcedateposition As Long, actualsourcecolumn As Long, targetdateposition As Long 
Dim Copysource As Range, pastetarget As Range 

TargetValue = dumpsheet.Cells(rows.Count, 1).End(xlUp).row 
sourcedateposition = dumpsheet.Cells(rows.Count, 5).End(xlUp).row 
targetdateposition = dumpsheet.Cells(rows.Count, 7).End(xlUp).row 

'Loop Source Column 
For F = 1 To sourcedateposition 
SourceColumnValue = dumpsheet.Cells(F, 5).Value 
     'Get Target Column Match to Source 

       ' Loop to compare strings 
        For P = 1 To targetdateposition 
        targetcolumnvalue = dumpsheet.Cells(P, 7).Value 
        If targetcolumnvalue = SourceColumnValue Then 

         TargetColumnRange.Value = SourceColumnValue 
         targetcolumnvalue = dumpsheet.Cells(P, 8).Value 
         sourcecolumnnumber = dumpsheet.Cells(F, 6).Value 

         For O = 1 To dumpsheet.Cells(rows.Count, "a").End(xlUp).row 
          If O > 1 Then 
          Sourcename = dumpsheet.Cells(O, 1).Value 
          sourcerow = dumpsheet.Cells(O, 2).Value 
          targetrow = dumpsheet.Cells(O, 3).Value 

          'Set Integers 
          actualsourcerow = CInt(sourcerow) 
          actualtargetrow = CInt(targetrow) 
          actualtargetcolumn = CInt(targetcolumnvalue) 
          actualsourcecolumn = CInt(sourcecolumnnumber) 


          'Copy and Paste 
          Set Copysource = SourceSheet.Cells(actualsourcerow, actualsourcecolumn) 
          Set pastetarget = TargetSheet.Cells(actualtargetrow, actualtargetcolumn) 
          Copysource.Copy 
          pastetarget.PasteSpecial (xlPasteValues) 
          End If 
         Next O 
        End If 
       Next P 
Next F 
+0

Спасибо, что вернулись и закрыли это - молодец! – brettdj

2

Использование FIND с дат finnicky см here

Ваш код работал на моем испытание, когда я изменил

Set TargetColumnRange = dumpsheet.Range("G2:G" & TargetValue).Find(what:=SourceColumnValue, _ 
                  LookIn:=xlFormulas, _ 
                  LookAt:=xlWhole, _ 
                  SearchOrder:=xlByRows) 

в

Set TargetColumnRange = dumpsheet.Range("G2:G" & TargetValue).Find(what:=DATEVALUE(SourceColumnValue), _ 
                  LookIn:=xlFormulas, _ 
                  LookAt:=xlWhole, _ 
                  SearchOrder:=xlByRows) 
+0

Гений, спасибо! – PootyToot

+0

Nope - просто опытный :) Спасибо за быстрое закрытие. – brettdj

+0

Это действительно смешно, я запускал его во второй раз, и он пропустил даты, когда он работал. Я сбросил excel и перезапустил и снова попробую – PootyToot