【问题标题】:Selecting Ranges in Excel VBA在 Excel VBA 中选择范围
【发布时间】:2012-08-24 00:13:51
【问题描述】:

我想创建一个 VBA 子例程,在表中搜索名为“Phonetic Name”的第一列标题。然后在右下角的表格中找到绝对最后一个单元格,并存储一个变量作为最后一个单元格上方一行的单元格坐标。然后子程序将选择第一个单元格“Phonetic Name”和“LastCell”变量之间的所有单元格。

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 友好的方式重写此逻辑?

【问题讨论】:

  • 那段代码有什么问题?
  • 我认为 ActiveSheet.Range(TL,LastCell).Copy 是您要查找的内容(但请从 .Find() 行的末尾删除 .Row

标签: excel vba


【解决方案1】:
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

【讨论】:

  • 将 TL 更改为 TL.Row,即,将 LastCol = .Cells(TL, Columns.Count).End(xlToLeft).Column 更改为 LastCol = .Cells(TL.Row, Columns.Count).End(xlToLeft).Column 另外,请考虑扩展您的 With 语句以包含所有 ActiveSheet 引用,并声明所有变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 2018-11-11
  • 1970-01-01
相关资源
最近更新 更多