2012-08-24 188 views
0

我想創建一個VBA子例程,該子例程在表中搜索名爲「Phonetic Name」的第一個列標題。然後找到表格右下角的絕對最後一個單元格,並在最後一個單元格的上一行存儲一個變量作爲單元格座標。子程序將選擇第一個單元格「Phonetic Name」和「LastCell」變量之間的所有單元格。在Excel中選擇範圍VBA

Dim LastCol As Integer 

TL = ActiveSheet.Range("A:A").Find("Phonetic Name", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True).Row 

Set LastRow = Cells.Find("*", [a1], , , xlByRows, xlPrevious) 

With ActiveSheet 
    LastCol = .Cells(TL, .Columns.Count).End(xlToLeft).Column 
End With 

Set LastCell = ActiveSheet.Cells(LastRow.Row - 1, LastCol) 
'I would like to do something like the following... 
ActiveSheet.Range("TL:LastCell").Select 
Selection.Copy 

如何以VBA友好的方式重新編寫此邏輯?

+0

該代碼有什麼問題? – ApplePie

+1

我想'ActiveSheet.Range(TL,LastCell).Copy'是你在找什麼(但是從'.Find()'行的末尾刪除'.Row') –

回答

2
Dim LastCol As Integer 
Dim TL as Range 

Set TL = ActiveSheet.Range("A:A").Find("Phonetic Name", _ 
       LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True) 

If Not TL Is Nothing Then 

    Set LastRow = Cells.Find("*", [a1], , , xlByRows, xlPrevious) 
    With ActiveSheet  
     LastCol = .Cells(TL.Row, .Columns.Count).End(xlToLeft).Column 
    End With 
    Set LastCell = ActiveSheet.Cells(LastRow.Row - 1, LastCol) 
    ActiveSheet.Range(TL,LastCell).Copy 

End If 
+0

謝謝,但我得到一個鍵入與代碼不匹配的錯誤。 – AME

+0

您是否將TL聲明更改爲'As Range'?編輯我的帖子,以表明... –

+0

是的,我做到了。不知道爲什麼我仍然得到相同的錯誤。 – AME