简体   繁体   English

VBA代码在不同的工作簿中的工作方式有所不同

[英]VBA Code works differently in different workbooks

Hello I have a simple VBA code, which copies a column and pastes it in another column without the empty cells, which are in the original column. 您好,我有一个简单的VBA代码,该代码复制一列并将其粘贴到另一列中,而原始列中没有空单元格。 It works in the woorkbook, where I wrote it. 它可以在我写它的woorkbook中使用。 But I copied it to another one, where I need it. 但是我将其复制到需要的其他位置。 It copies the the needed cells more than once and it fills the whole column the these values. 它多次复制所需的单元格,并将这些值填满整列。

Range("f5:f2500").ClearContents                             

 With Range("d5:d2500")                                      

    .Offset(, 0).SpecialCells(xlCellTypeFormulas, _  
    xlNumbers).Copy                                                 
    .Offset(, 2).PasteSpecial skipblanks:=True, _            
    Paste:=xlPasteValues                                            

 End With

The Sub below will copy the formulas (with values in cells) from column D, and paste their values in column F, starting from Cell "F5" and down (without blanks). 下面的Sub将复制D列中的公式(单元格中包含值),并将其值粘贴到F列中,从“ F5”单元格开始向下(无空格)进行粘贴。

The Sub receives the Worksheet.Name as an argument, so all the Range s inside are fully qualified with that certain worksheet's name. Sub接收到Worksheet.Name作为参数,因此内部的所有Range都完全符合该特定工作表的名称。

Code

Option Explicit

Sub CopyColumnWOBlanks(wsName As String)

With Worksheets(wsName)
    .Range("F5:F" & .Cells(.Rows.Count, "F").End(xlUp).Row).ClearContents

    .Range("D5:D" & .Cells(.Rows.Count, "D").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlNumbers).Copy
    .Range("F5").PasteSpecial Paste:=xlPasteValues, skipblanks:=True
End With

End Sub

This Main sub below, is just for testing, modify it to fit your needs. 下面的Main子项仅用于测试,请对其进行修改以适合您的需求。

Sub Main()

CopyColumnWOBlanks ("Sheet5") ' <-- change "Sheet5" to whatever worksheet you want the macro to run

End Sub

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

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