我在VBA中选择一系列单元格时遇到了困难。我已经有一系列分散的细胞,但我正在尝试将三个细胞添加到选择范围内每个细胞的右侧。
到目前为止,我已尝试过:
SelectedRange("Hi").Resize(1, 4).Select
,运行时出错;我认为它不起作用,因为SelectedRange是一个范围而不是一个单元格。
SelectedRange()搜索输入字符串并返回与输入匹配的每个单元格的范围,该输入是此代码的修改版本:http://www.thespreadsheetguru.com/the-code-vault/2014/4/21/find-all-instances-with-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
感谢。
答案 0 :(得分:2)
您尚未透露完全 SelectedRange 引用的内容;希望它不是不连续细胞的结合。
在With...End With statement中使用 SelectedRange ,您可以访问Resize property的维度。
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 property并调整每个单元格,同时将其添加到Union method的集合中。
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
有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros。