使用VBA在Excel中从命名区域自动填充到未命名的目标
我正尝试从命名范围自动填充到其右侧的相邻单元格。 原始的范围包含组合的单元格,大小为4x4
。 我的问题是, Autofill
方法需要一个Destination:=Range("...")
,并不需要像Destination:=xlSameAreaToTheRight
。
解决办法是,如果我可以做类似的事情
Range("origin").AutoFill Destination:=( Range("origin").Area + Rows(4) ), _ Type:=xlFillDefault
那么怎样才能find格式为A1:D4
的命名区域的行和列,并添加如4列?
Thnks为您的支持!
我不确定你想得到什么结果,但这里是你的特定问题的答案:
您可以使用.Address
获取格式为$ A $ 1:$ D $ 4的.Address
,并获取列的数量只需将.Columns.Count
添加到指定的范围。 (使用偏移量应该是没有问题的将列的数量添加到您的范围内的活动单元格。
Dim TestRange As String Dim AmountColumns As Integer TestRange = ActiveWorkbook.Sheets(1).Range("Test").Address AmountColumns = ActiveWorkbook.Sheets(1).Range("Test").Columns.Count
感谢stema的回答,我find了一个(非常简单)的解决scheme:
要将行或列添加到命名的范围,并将其用作自动填充目标,可以简单地执行
Range("origin").AutoFill Destination:=( Range("origin").Range("A1:H2") ), _ Type:=xlFillDefault
什么会自动填充四列和两行到我们的“原点”:
| 1 | 2 | | 1,1 | 1,2 | 2,1 | 2,2 |
这导致:
| 1 | 2 | 3 | 4 | | 1,1 | 1,2 | 2,1 | 2,2 | 2,7 | 3,12 | 3,54 | 3,96 |
这里有一个方法来使用@ stema的build议。
Sub namedfill() Dim locOrig As String Dim firstCell As String Dim lastCell As String 'Pluck address of top-left and bottom-right cells from .Address string locOrig = Range("Origin").Address firstCell = Left(locOrig, 4) lastCell = Right(locOrig, 4) Range("Origin").AutoFill Destination:=Range(firstCell, Range(lastCell).Offset(0, 4)), Type:=xlFillDefault End Sub