excel - 将用户定义的范围插入另一个工作表

标签 excel vba

我设置了一个范围,可以用 msg 框和 rng.address 显示它,但我无法复制/插入或用 i 做任何事情。在我的代码片段中,我尝试复制它,但后来我总是需要在另一张表中的第一列之后插入范围。

这是一个特殊的问题。我确信这很容易,或者我只是误解了事情。我也不明白

Dim rng As Range


Set rng = Application.InputBox("Please choose a range", "Obtain Range Object", Type:=8)

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

continue:


Worksheets("Sheet source").Range(rng).Copy Worksheets("sheet destination").Range("A1").Paste

最佳答案

您声明了 Dim rng As Range,因此已经是特定工作表中的范围,因此 Range(rng) 不起作用,因为 Range() 等待地址作为参数(而不是范围)。

此外,如果您在一行中使用 .Copy 语法(以目标作为参数),则不需要 .Paste

应该是

rng.Copy Worksheets("sheet destination").Range("A1")

同时使用Goto(在错误处理之外)是一种非常糟糕的做法。相反,使用类似的东西:

Sub AskMe()
    Dim Rng As Range

    Do
        On Error Resume Next 'next line throws error if user presses cancel so we hide **all** error messages now (and turn them on later!)
        Set Rng = Application.InputBox("Please choose a range", "Obtain Range Object", Type:=8)
        If Err.Number <> 0 Then Exit Sub 'if an error occurred then the user pressed cancel (so we exit)
        On Error GoTo 0 'always re-activate error reporting! Otherwise all error messages stay hidden.
    Loop Until MsgBox("Your choice " & Rng.Address & " ?", vbYesNo, "Confirm") = vbYes
    'repeat asking for a range until yes is pressed

    Rng.Copy Worksheets("sheet destination").Range("A1")
End Sub

关于excel - 将用户定义的范围插入另一个工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53168742/

相关文章:

Excel - 数字通配符有助于对值进行分组?

Excel VBA循环遍历范围并删除空格和空格之前的文本

excel - 计算两列之间的匹配

php - 将数据从Mysql传输到Excel

vba - VB6如何知道锁定的文件进程

excel - 从 VBA 添加引用导致出现密码提示

mysql - 如何将相同的 IF 语句应用于同一列中的多个单元格? (Excel)

vba - VBA Winsock无法使用更长的端口长度(sin_port)

excel - 尝试根据上面的数字用字母字符填充空白

excel - VBA 以编程方式修复 "errored"单元格?