2016-09-06 28 views
0

我對VBA很新穎。我正在嘗試編寫一個宏,它將在所有標題名稱(第1行中的所有變量名稱)中搜索單詞「date」,並將單元格(從另一個工作表)複製到找到匹配項的標題下的行(第2行)。如何查找字符串關鍵字並在匹配字符串時將其粘貼到它下面的行?

粘貼部分目前無法正常工作,我正在搜索整個工作簿,因爲我不知道如何將其設置爲僅搜索標題行。

Sub FindAndPaste() 

Dim Sheet As Worksheet 
Dim Loc As Range 

For Each Sheet In ThisWorkbook.Worksheets 
    With Sheet.UsedRange 
    Set Loc = .Cells.Find(What:="date") 
    If Not Loc Is Nothing Then 
     Do Until Loc Is Nothing 
      Sheets("Sheet1").Range("L3").Copy 
      Loc.Value.Offset(1, 0).PasteSpecial xlPasteAll 
      Set Loc = .FindNext(Loc) 
     Loop 
    End If 
End With 
Set Loc = Nothing 
Next 
End Sub 

我也試圖通過其更改爲下面的代碼改變了裏面做的一部分,直到環,但似乎並沒有擦出火花。

Do Until Loc Is Nothing 
    copiedval = Sheets("Sheet1").Range("L3").Copy 
    Loc.Value.Offset(1, 0).Value = copiedval 
    Set Loc = .FindNext(Loc) 
Loop 

回答

2

這將是不使用查找更簡單()

目前尚不清楚是否你正在尋找這包含日期,或與價值「日期」只是細胞。

或者你是否想從搜索中排除Sheet1中

Sub FindAndPaste() 

    Dim Sheet, wb As workbook 
    Dim c As Range, arrSheets 

    Set wb = ThisWorkbook 

    arrSheets = Array(wb.sheets("Sheet2"), wb.sheets("Sheet3")) 

    For Each Sheet In arrSheets 
     For Each c in Sheet.UsedRange.Rows(1).Cells 
      If c.value like "*date*" Then 
       wb.Sheets("Sheet1").Range("L3").Copy c.Offset(1,0) 
       c.Offset(1,0).NumberFormat = "yyyy/mm/dd" '<<<<<<<<<EDIT 
      End If 
     Next c 
    Next 
End Sub 
+0

Yesss!就是這個!謝謝@蒂姆·威廉姆斯 –

+0

我明白你的意思是排除表1的搜索。我實際上只是需要它通過兩張不同的紙張,所以我只複製了這個宏兩次,並將該紙張設置爲一個宏中的工作表2,並在另一個「設置工作表=工作表(」工作表2「)中將工作表3設置爲'我需要它包含單詞「日期」,就像您編碼它一樣。 –

+1

如果您只需要搜索兩張紙,請參閱我的編輯。 –

1

試試這個

Sub FindAndPaste() 

Dim sht As Worksheet 
Dim Loc As Range, founds As Range 
Dim firstAddress As String 

For Each sht In ThisWorkbook.Worksheets 
    Set founds = sht.Cells(2,1) 
    With Intersect(sht.Rows(1), sht.UsedRange) 
     Set Loc = .Find(What:="date", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False) 
     If Not Loc Is Nothing Then 
      firstAddress = Loc.Address 
      Do 
       Set founds = Union(founds, Loc) 
       Set Loc = .FindNext(Loc) 
      Loop While Not Loc.Address <>firstAddress 
      Intersect(.Cells,founds).Offset(1).Value =Sheets("Sheet1").Range("L3").Value 
     End If 
    End With 
Next sht 

End Sub 

而如果你需要找到一個頭方含「日期」比剛剛替補LookAt:=xlWholeLookAt:=xlPart

相關問題