繁体   English   中英

将范围作为变量从一张纸插入到另一张纸

[英]Insert range as variable from one sheet to another

我现在正在寻找一个比我愿意管理的解决方案更长的时间,所以这就是我的问题。

我需要在第一列之后将大部分为 2 行的列的动态范围插入到另一个工作表中。 我无法对列进行硬编码,因此我创建了一个 Application.InputBox,用户必须在其中选择范围,然后确认他的选择。 现在,如果我使用范围并使用 rng.address 制作一个 msg 框,它会显示范围 eG A$B$。

现在,当我尝试插入范围时,根据我尝试的方式,我会收到各种错误。

我目前的方法如下:

dim rng as Range
         retry:
Set rng = Application.InputBox("Do that and that", "Obtain Range Object", Type:=8)

 If MsgBox("Your choice " & rng.Address & " ?", vbYesNo, "Confirm") = vbYes Then
    GoTo continue:
    Else
    GoTo retry:
    End If

         continue:

'#1) i tried this:
Worksheets(templateold).Range(rng).Insert Shift:=xlToRight Worksheets(templatenew).Range(rng)

'#2) and i tried that:
Worksheets(templateold).Range(rng).Copy Worksheets(templatenew).Range(rng)

我尝试选择拳头然后复制,但没有任何效果。 :(

如何使用存储在变量中的范围将范围插入到另一个工作表中? 对不起,如果我的代码片段不好,我在工作中尝试了更多的东西,但我家里没有所有东西。

以下将复制用户选择的范围,然后通过将其他所有内容向右移动将其插入到 B 列中的另一个工作表中:

Sub foo()
Application.ScreenUpdating = False

Dim templateold As Worksheet: Set templateold = ThisWorkbook.Worksheets("Sheet1")
Dim templatenew As Worksheet: Set templatenew = ThisWorkbook.Worksheets("Sheet2")
'declare and set the worksheets you are working with, amend as required.
Dim rng As Range

retry:
Set rng = Application.InputBox("Do that and that", "Obtain Range Object", Type:=8)

If MsgBox("Your choice " & rng.Address & " ?", vbYesNo, "Confirm") = vbYes Then
    rng.Copy
    templateold.Range("B:B").Insert Shift:=xlToRight
Else
    GoTo retry:
End If

Application.ScreenUpdating = True
End Sub

假设我们有两张工作表,Sheet1(复制源)和 Sheet2(粘贴目标)。 我们知道数据从哪里开始(wsSource 上的 A1),但数据可能有 4 列,也可能有 40 列(与行相同)。

当您想要查找特定范围内的最后一行或最后一列时,我们使用 CurrentRegion.Rows/Columns.Count 它将以 long 形式返回最后一行/列。

Sub DuplicateRange()
Dim wsSource As Worksheet, wsTarget As Worksheet
Dim lRow As Long, lCol As Long

Set wsSource = ThisWorkbook.Sheets("Sheet1")
Set wsTarget = ThisWorkbook.Sheets("Sheet2")

' We know A1 is the starting (top-left) cell. _
using CurrentRegion.Rows/Columns.Count we can _
find the range of data without hardcoding the columns
lRow = wsSource.Range("A1").CurrentRegion.Rows.Count
lCol = wsSource.Range("A1").CurrentRegion.Columns.Count

' Range(A1:lCol,lRow)
With wsSource.Range(Cells(1, 1), Cells(lRow, lCol))
    .Copy wsTarget.Cells(1, 1)
End With
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM