简体   繁体   English

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

[英]Copy data up to last used column with vba

I was successfully able to copy data up to the last used row using VBA.我成功地使用 VBA 将数据复制到最后使用的行。 I am trying to do the same thing but copy data from A1 to LastColumn2.我正在尝试做同样的事情,但将数据从 A1 复制到 LastColumn2。 Here is the code I have put together thus far:这是我到目前为止放在一起的代码:

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.这只是代码的一部分 - 所有变量都已正确标注尺寸。

You are getting the error because LastColumn is number.您收到错误是因为LastColumn是数字。 You want the string equivalent of it ie the column name.您需要与它等效的字符串,即列名。 For Further Reading 进一步阅读

Avoid the use of .Select and fully qualify your objects.避免使用.Select并完全限定您的对象。 INTERESTING READ 有趣的阅​​读

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

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希望它有帮助

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

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