VBA不断更新范围的列号

时间:2018-06-26 13:46:04

标签: excel vba excel-vba

我想复制每个工作表中的数据,然后将其复制到一个名为scrap的新工作表中,我想调整每个工作表中所选内容的粘贴位置,我想在rr变量中执行此操作,但是我遇到错误。在迭代过程中如何连续更改行号?

Sub Macro1()

Dim ws As Worksheets 
Dim starting_ws As Worksheet
Set starting_ws = ActiveSheet 
ws_num = ThisWorkbook.Worksheets.Count - 2

For I = 1 To ws_num
    e = 9
    s = 39
    ThisWorkbook.Worksheets(I).Activate
    Range("A9:J39").Select
    Selection.Copy
    rr = "A" + CStr(s) + ":" + "J" + CStr(e)
    Worksheets("scrap").Range(rr).Paste
    e = e + 30
    s = s + 30
   Next
End Sub

2 个答案:

答案 0 :(得分:3)

VBA中的字符串连接运算符为&,而不是+。因此,请尝试:

rr = "A" & CStr(s) & ":" & "J" & CStr(e)

有两点需要进一步改进:


通常,这应该可以满足以下要求:

Sub TestMe()

    Dim counter As Long
    Dim wsTotal As Long

    wsTotal = ThisWorkbook.Worksheets.Count - 2

    Dim starting As Long: starting = 9
    Dim ending As Long: ending = 39

    Dim ws As Worksheet
    Dim rangeToCopy As Range

    For counter = 1 To wsTotal
        Set ws = ThisWorkbook.Worksheets(counter)
        With ws
            Set rangeToCopy = .Range(.Cells(starting, "A"), .Cells(ending, "J"))
            rangeToCopy.Copy ThisWorkbook.Worksheets("scrap").Range(rangeToCopy.Address)
        End With

        starting = starting + 30
        ending = ending + 30
    Next counter

End Sub

答案 1 :(得分:0)

粘贴操作的目标只需要左上角的单元格,而单个目标实际上是range.Copy操作的参数。

工作表 s 是一个集合,您需要工作表(单数)

Sub Macro1()
    Dim starting_ws As Worksheet
    dim rr as string, I as long, e as long, ws_num as long

    'I have no idea what you want to do with this after initializing it
    Set starting_ws = ActiveSheet 

    ws_num = ThisWorkbook.Worksheets.Count - 2

    e = 9
    For I = 1 To ws_num
        rr = "A" & CStr(e)
        with ThisWorkbook.Worksheets(I)
            .Range("A9:J39").Copy _
                destination:=Worksheets("scrap").Range(rr)
         end with
         e = e + 31   'there are 31 rows in A9:J39
    Next i
End Sub

声明变量。进入VBE的“工具”,“选项”,然后在“需要变量声明”旁边打勾。