使用 vba 将数据复制到最后使用的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20528794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:54:37  来源:igfitidea点击:

Copy data up to last used column with vba

vbaexcel-vbaexcel

提问by ncarroll

I was successfully able to copy data up to the last used row using VBA. I am trying to do the same thing but copy data from A1 to LastColumn2. Here is the code I have put together thus far:

我成功地使用 VBA 将数据复制到最后使用的行。我正在尝试做同样的事情,但将数据从 A1 复制到 LastColumn2。这是我迄今为止整理的代码:

Sheets("Results").Select
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
Range("A1:" & LastColumn & "2").Select
Selection.Copy

The debugger highlights the third line. This is just a portion of the code - All of the variables have been dimensioned properly.

调试器突出显示第三行。这只是代码的一部分 - 所有变量都已正确标注尺寸。

Thanks!

谢谢!

回答by Siddharth Rout

You are getting the error because LastColumnis number. You want the string equivalent of it i.e the column name. For Further Reading

您收到错误是因为LastColumn是数字。您需要与它等效的字符串,即列名。进一步阅读

Avoid the use of .Selectand fully qualify your objects. INTERESTING READ

避免使用.Select并完全限定您的对象。有趣的阅​​读

Is this what you are trying?

这是你正在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim LastCol As Long
    Dim LastColumn As String

    Set ws = ThisWorkbook.Sheets("Results")

    With ws
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        '~~> Return column name from number
        LastColumn = Split(.Cells(, LastCol).Address, "$")(1)

        Set rng = .Range("A1:" & LastColumn & "2")

        Debug.Print rng.Address

        rng.Copy
    End With
End Sub

回答by bto.rdz

The problem is that the range you are passing is wrong because it is wating simething like:

问题是您传递的范围是错误的,因为它正在等待类似以下内容:

Range("A1:C2").Select

and you are passing:

你正在通过:

Range("A1:32").Select

So what you can do is:

所以你可以做的是:

Range(cells(1,1),cells(2,lastcolumn)).Select

Cell(1,1) = A1 beacuse its is row number 1 column number 1

Cell(1,1) = A1 因为它是行号 1 列号 1

As mentioned it is better if you just

如上所述,如果你只是更好

Range(cells(1,1),cells(lastcolumn,2)).copy

Hope it helps

希望能帮助到你