在VBA中循环以接收下一个小区

时间:2018-06-07 15:44:55

标签: vba excel-vba loops excel

我想知道你是否可以提供帮助,我有两张表' Masterfile'和'帐户'目的是复制帐户工作表中从A2开始的每个单元帐号,并将其复制到主文件工作表的B6中。我需要将文件保存在我的桌面上,我已经编写了一些代码,但我似乎无法理解如何从帐户中选择单元格 - 复制到B6 - 保存然后移动到下一个单元格。有人可以帮忙吗?

Private Sub LOOPCELL()

Dim ws1 As Worksheet
Set ws1 = Sheets("Accounts")

Dim ws2 As Worksheet
Set ws2 = Sheets("Masterfile")

Dim lastRow As Integer
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

ws1.Range("A2:A" & lastRow).Copy Destination:=ws2.Range("B6")

Dim filepath1 As String
Dim Filename1 As String
Dim Filename2 As String
Dim Filename3 As String
Path = "C:\Users\mukhan\Desktop"
Filename1 = Range("B6")
Filename2 = Range("D6")
Filename3 = Range("C8")

ActiveWorkbook.SaveAs Filename:=Path & Filename1 & "-" & Filename2 & "-" & 
Filename3 & ".xlsb", FileFormat:=xlExcel12, CreateBackup:=False

End With
End Sub

1 个答案:

答案 0 :(得分:1)

我必须做一些假设,因为你的问题不是很具体。主要的是我的代码假定两个文件都在同一个工作簿中。

它选择“帐户”中的范围A2:A__(直到A列中的最后一个填充值),并将所有数据一次性复制到从B6开始的“主文件”。

Sub CopyRange()

    Dim ws1 As Worksheet
    Set ws1 = Sheets("Accounts")

    Dim ws2 As Worksheet
    Set ws2 = Sheets("Masterfile")

    Dim i As Integer
    For i = 2 To ws1.Cells(ws1.Rows.count, "A").End(xlUp).row
        ws1.Range("A" & i).Copy Destination:=ws2.Range("B6")
        ActiveWorkbook.SaveAs Filename:="C:\Users\mukhan\Desktop\Account " & ws1.Range("A" & i).Value2 & ".xlsb", FileFormat:=xlExcel12, CreateBackup:=False
    Next i

End Sub