简体   繁体   English

具有动态范围的VBA复制/粘贴值到另一个工作簿中,包括动态文件路径查找

[英]VBA Copy/Paste values with dynamic range into another Workbook, including dynamic file path lookup

Lengthy title but hopefully I can explain. 标题冗长,但希望我能解释。 What I am wanting to do is Copy/Paste values from active Workbook into another Workbook contained in the same directory "folder" as the active. 我要执行的操作是将活动工作簿中的值复制/粘贴到活动文件夹所在的同一目录“文件夹”中的另一个工作簿中。 I need the range of the copy to be dynamic in the sense that if I add lines to the current range, I want the code to automatically pick this up and not have to manually amend the range in the code. 从某种意义上说,我需要副本的范围是动态的,如果我将行添加到当前范围中,则我希望代码自动选择此范围,而不必手动修改代码中的范围。

I managed to find and slightly some code on StackOverflow which does what I need statically, but I have no idea how to add the various "dynamic" needs as my VBA knowledge is unfortunately not advanced enough. 我设法在StackOverflow上找到了一些代码,这些代码静态地完成了我所需要的,但是我不知道如何添加各种“动态”需求,因为不幸的是,我的VBA知识还不够先进。 If you are able to assist, thanks very much in advance! 如果您能提供帮助,请非常感谢!

Code: 码:

Public Sub CopyData()
Dim x As Workbook
Dim y As Workbook
Dim vals As Variant
Dim RemoveRows

Below is where I need the "Path" of the new Workbook to be dynamic. 下面是我需要新工作簿的“路径”动态的地方。 I thought maybe along the lines of Application.ActiveWorkbook.Path to find the path, as I've seen that before, but I couldn't really get it to work. 我认为可能是按照Application.ActiveWorkbook.Path的路径来查找路径,正如我之前所看到的那样,但是我无法真正使它正常工作。 It then also needs to add the filename extension of the destination Workbook, which I have specified on "Sheet 1" in cell F2 of the Active Workbook. 然后,它还需要添加目标工作簿的文件扩展名,该扩展名是我在活动工作簿的单元格F2中的“表1”上指定的。 ie the destination Workbook to open would be "ActiveWorkbook.Path + Sheet 1 cell F2 + .xls" if that makes sense. 也就是说,如果可以的话,要打开的目标工作簿应为“ ActiveWorkbook.Path +工作表1单元格F2 + .xls”。 The reason for cell F2 is so that I can use this code with other Workbook names. 使用F2单元格的原因是,我可以将此代码与其他Workbook名称一起使用。

'Open workbook first:
Set x = Workbooks.Open("PATH")

Continue through code. 继续执行代码。

Set y = ThisWorkbook

Below Range is what I need to also be dynamic, ideally it would look in column A (starting in row 4), and create a copy/store range for all columns AP until the first blank cell is located in A (ie exactly as per below, but the 13 should automatically increase to say 15 if I add 2 more rows with text in column A. 在Range下面,我还需要保持动态,理想情况下,它会在A列中查找(从第4行开始),并为所有AP列创建一个复制/存储范围,直到第一个空白单元格位于A中(即与下面的内容,但是如果我在A列中再添加2行包含文本的行,则13应该会自动增加为15。

'Store values in a variable:
vals = y.Sheets("Sheet1").Range("A4:P13").Value

Continue through code (paste/variable assign would need to be the exact same range as vals above except offset up by 2, ie should be A2 to P11 or P13 if rows added). 继续执行代码(粘贴/变量分配必须与上面的val完全相同,但偏移量要增加2,即,如果添加行,则应为A2至P11或P13)。

'Use the variable to assign a value to the other file/sheet:
x.Sheets("Sheet2").Range("A2:P11").Value = vals

'Delete Zero Rows
Set x = ActiveWorkbook
x.Sheets("Sheet2").Activate
For RemoveRows = Range("K65536").End(xlUp).Row To 1 Step -1
   If Cells(RemoveRows, 11).Value = 0 Then Rows(RemoveRows).EntireRow.Delete

Next RemoveRows

'Copy Paste Values Again to Sheet 1 to ensure formatting uncompromised
vals = x.Sheets("Sheet2").Range("A2:P1000").Value
x.Sheets("Sheet1").Range("A2:P1000").Value = vals
x.Sheets("Sheet2").Cells.Clear
x.Sheets("Sheet1").Activate

'Close x:
If x.Saved = False Then
    x.Save
End If
x.Close

End Sub

For the first question relating to the path, you are almost there, you just need to build the full string. 对于与路径有关的第一个问题,您已经差不多了,只需要构建完整的字符串即可。 The Application.activeworkbook.path returns the string that point to the directory of the activeworkbook, so you just need to addon the name of the file Application.activeworkbook.path返回指向activeworkbook目录的字符串,因此您只需要添加文件名即可

For the dynamic ranges, you can use the Range.End property 对于动态范围,可以使用Range.End属性

For the transfer between worksheets/books I would suggest using the Range.Copy/paste properties. 对于工作表/书籍之间的转移,我建议使用Range.Copy / paste属性。 when pasting a range, you just need to specify the top left cell and excel will take care of the rest 粘贴范围时,只需指定左上角的单元格,Excel就会处理其余的单元格

I've made a few updates to make the worksheet references more explicit, avoid .activate, and a few other changes, but something like the below should do it: 我进行了一些更新,以使工作表引用更明确,避免使用.activate和其他一些更改,但是应该执行以下操作:

Public Sub CopyData()
    Dim x As Workbook
    Dim y As Workbook
    Dim xWs1 As Worksheet
    Dim xWs2 As Worksheet
    Dim yWs As Worksheet
    Dim vals As Range
    Dim newVals As Range
    Dim RemoveRows
    Dim Path As String

    'build the Path
    Path = Application.ActiveWorkbook.Path & "\file.xlsx" 'as an alternative you could use the Application.FileDialog(msoFileDialogOpen) to promt the user to select the file

    'Open workbook first:
    Set x = Workbooks.Open(Path)
    Set xWs1 = x.Sheets("Sheet1")
    Set xWs2 = x.Sheets("Sheet2")

    Set y = ThisWorkbook
    Set yWs = y.Sheets("Sheet1")

    'reference values by a range:
    Set vals = yWs.Range("A4:P" & yWs.Range("A4").End(xlDown).Row)
    'copy/paste the range other file/sheet:
    vals.Copy xWs2.Range("A2")



    'Delete Zero Rows
    For RemoveRows = xWs2.Range("A2").End(xlDown).Row To 2 Step -1
        If xWs2.Cells(RemoveRows, 11).Value = 0 Then
            xWs2.Rows(RemoveRows).EntireRow.Delete
        End If
    Next RemoveRows

    'Copy Paste Values Again to Sheet 1 to ensure formatting uncompromised
    Set newVals = xWs2.Range("A2:P" & xWs2.Cells(1048576, 1).End(xlUp).Row)
    newVals.Copy xWs1.Range("A2")
    xWs2.Rows.EntireRow.Delete
    xWs1.Activate

    'Close x:
    If x.Saved = False Then
        x.Save
    End If
    x.Close

End Sub

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

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