2017-06-08 106 views
0

我对编程相当新,甚至更新VBA。添加简单的内容到动态单元格范围VBA

我试图在“A1”和“零售商名称”中的“零售商”中添加一列到“A2:Last_Relevant_Cell_In_A”电子表格的开头。

这是我到目前为止有:

Sub AddRetailerName() 

Dim WS_Target As Worksheet 
Dim WS_Target_Lastrow As Long 

Set WS_Target = Worksheets("Sheet1") 

'Find last row of WS_Target 
WS_Target_Lastrow = WS_Target.Cells.Find("*", [A1], , , _ 
xlByRows, xlPrevious).Row 

'find last column of WS_Target 
WS_Target_Lastcol = WS_Target.Cells.Find("*", [A1], , , _ 
xlByColumns, xlPrevious).Column 

Range("A:A").EntireColumn.Insert 
Range("A1").FormulaR1C1 = "Retailer" 
Range(Cells(2, 1), Cells(WS_Target_Lastcol, 1)).FormulaR1C1 = "RetailerName" 


End Sub 

这只是将内容插入 “A1:A6”。插入的信息是正确的,但它应该动态插入电子表格中找到的行数(在本例中为950)。

任何想法如何我可以解决这个问题?

注意:虽然此操作只需点击几下鼠标(无VBA)即可完成,但我计划一次在大约20个电子表格中使用它。

回答

0

你应该改变

Range(Cells(2, 1), Cells(WS_Target_Lastcol, 1)).FormulaR1C1 = "RetailerName" 

Range(Cells(2, 1), Cells(WS_Target_Lastrow, 1)).FormulaR1C1 = "RetailerName" 

(我假设你最近使用的电池是F列?这可以解释你的代码填充到第6行。)


这也是一个好主意,以确定您的RangeCells(等)方法与工作ksheet它们指的,所以我建议改变你的代码:

Sub AddRetailerName() 

    Dim WS_Target As Worksheet 
    Dim WS_Target_Lastrow As Long 
    Dim WS_Target_Lastcol As Long 

    Set WS_Target = Worksheets("Sheet1") 

    With WS_Target ' allows us to use "." instead of "WS_Target." 
     'Find last row of WS_Target 
     WS_Target_Lastrow = .Cells.Find("*", [A1], , , _ 
             xlByRows, xlPrevious).Row 

     'find last column of WS_Target 
     WS_Target_Lastcol = .Cells.Find("*", [A1], , , _ 
             xlByColumns, xlPrevious).Column 

     .Range("A:A").EntireColumn.Insert 
     'Use "Value" rather than "FormulaR1C1" to set a value 
     '.Range("A1").FormulaR1C1 = "Retailer" 
     '.Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).FormulaR1C1 = "RetailerName" 
     .Range("A1").Value = "Retailer" 
     .Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).Value = "RetailerName" 
    End With 
End Sub 

而只是FYI

.Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).Value = "RetailerName" 

也可以写成要么

.Range(.Cells(2, "A"), .Cells(WS_Target_Lastrow, "A")).Value = "RetailerName" 

.Range("A2:A" & WS_Target_Lastrow).Value = "RetailerName" 

它们每个都实现相同的事情,但不同的人更喜欢不同的编码风格。

+1

谢谢你与我一起经历这个。你的代码版本几乎可以工作。我最初有一个编译器错误。它在我在'WS_Target_Lastcol = .Find(“*”,[A1],,,''...')代码行中添加'.Cells'之前添加了'.Cells'。无论哪种方式,这是一个巨大的帮助!我也很感谢你们展示了以相同方式工作的不同版本的代码。经过一些实验后,我发现我更喜欢后者。可能因为它更简洁,但那只是我。再次感谢! –

+0

@JohnSmith - 糟糕 - 多么尴尬!我编辑了答案,因此没有人注意到我的错误。 – YowE3K

+0

@ YowE3K Lol。别担心!它让我思考并向自己证明,我知道代码中发生了什么。再次感谢! –

相关问题