select分散范围旁边的单元格

我很难在VBA中select一系列单元格。 我已经有了一系列分散的单元格,但是我试图将三个单元格添加到select范围内的每个单元格的右侧。

到目前为止,我已经尝试过: SelectedRange("Hi").Resize(1, 4).Select ,在运行时给出错误; 我认为它不工作,因为SelectedRange是一个范围,而不是一个单元格。

SelectedRange()searchinputstring,并返回与input相匹配的每个单元格的范围,这是该代码的修改版本: http : //www.thespreadsheetguru.com/the-code-vault/2014/4/21 /发现,所有情况与- VBA

 Function SelectedRange(ByVal fnd As String) As Range Dim FirstFound As String Dim FoundCell As Range, rng As Range Dim myRange As Range, LastCell As Range Set myRange = ActiveSheet.UsedRange Set LastCell = myRange.Cells(myRange.Cells.Count) Set FoundCell = myRange.find(what:=fnd, after:=LastCell) 'Test to see if anything was found If Not FoundCell Is Nothing Then FirstFound = FoundCell.Address Else GoTo NothingFound End If Set rng = FoundCell 'Loop until cycled through all unique finds Do Until FoundCell Is Nothing 'Find next cell with fnd value Set FoundCell = myRange.FindNext(after:=FoundCell) 'Add found cell to rng range variable Set rng = Union(rng, FoundCell) 'Test to see if cycled through to first found cell If FoundCell.Address = FirstFound Then Exit Do Loop Set SelectedRange = rng 'Report Out Message MsgBox SelectedRange.Cells.Count & " cell(s) were found containing: " & fnd Exit Function 'Error Handler NothingFound: MsgBox "No cells containing: " & fnd & " were found in this worksheet" End Function 

谢谢。

您尚未透露SelectedRange引用的内容; 希望这不是一个不连续的细胞联盟。

在With … End With语句中使用SelectedRange ,您可以访问Resize属性的尺寸 。

 dim SelectedRange as range set SelectedRange = range("B2:D4") with SelectedRange set SelectedRange = .resize(.rows.count, .columns.count + 3) end with SelectedRange.select 'might want to get away from this method 

对于不连续的单元格排列,您需要循环遍历Areas属性,并使用Union方法将其添加到集合中。

 Dim a As Long, selectedRange As Range, tmpRange As Range Set selectedRange = Selection Set tmpRange = selectedRange.Range("A1") With selectedRange For a = 1 To .Areas.Count With .Areas(a) Set tmpRange = Union(tmpRange, .Cells.Resize(.Rows.Count, .Columns.Count + 3)) End With Next a End With Set selectedRange = tmpRange selectedRange.Select 'might want to get away from this method 

请参阅如何避免使用Excel中的selectVBAmacros来获取更多的方法来摆脱依靠select和activate来实现您的目标。