将文件名复制到相邻列的长度范围(作为填充)宏

时间:2016-11-23 18:07:42

标签: excel-vba range vba excel

我想从D列的第一个空单元格指定一个文件名(比如说“CVC”)到该列的一行,该列与E列的最后一个非空行匹配(类似于填充程序)。但是,我在最后一行代码中遇到了复制方法的问题。这是我的尝试:

Dim WB As Workbook
Dim lastRow As Long

Set WB = Workbooks.Open(fileName:= _
        "C:\Users\gustavo\Documents\Minambiente\TUA\2015\Consolidar_base\CVC.xlsx")

WBname = Replace(WB.Name, ".xlsx", "") 

lastRow = ThisWorkbook.Sheets(1).Range("E" & Rows.Count).End(xlUp).Row

ThisWorkbook.Sheets(1).Range(Cells(Rows.Count, 4).End(xlUp).Offset(1, 0), "D" & lastRow).Value = WBname

目前,我的数据如下:

"column D" ¦ "Column E"
  valueD   ¦   ValueE
  valueD   ¦   ValueE
           ¦   ValueE
           ¦   ValueE
           ¦   ValueE 

运行宏后,数据如下所示

"column D" ¦ "Column E"
  valueD   ¦   ValueE
  valueD   ¦   ValueE
   CVC     ¦   ValueE
   CVC     ¦   ValueE
   CVC     ¦   ValueE --> Note that what I am coping is the filename CVC 

1 个答案:

答案 0 :(得分:1)

如果我正确理解你要做的事情(即将error: 'p_val_vec_main' was not declared in this scope 复制到D列的每个单元格中,从D列中最后一个使用过的单元格后面的行开始,到最后一次使用的行中结束列E)中的单元格,然后这应该工作:

WBName

设置值的行也可以写为:

Dim WB As Workbook
Dim lastRowD As Long
Dim lastRowE As Long
Dim WBname As String

Set WB = Workbooks.Open(fileName:= _
        "C:\Users\gustavo\Documents\Minambiente\TUA\2015\Consolidar_base\CVC.xlsx")

WBname = Replace(WB.Name, ".xlsx", "") 

With ThisWorkbook.Sheets(1)
    lastRowD = .Range("D" & .Rows.Count).End(xlUp).Row
    lastRowE = .Range("E" & .Rows.Count).End(xlUp).Row
    .Range(.Cells(lastRowD + 1, "D"), .Cells(lastRowE, "D")).Value = WBname
End With