将简单内容添加到动态单元格范围VBA

时间:2017-06-08 20:00:14

标签: vba excel-vba excel

我对编程很新,甚至比VBA更新。

我正在尝试在电子表格的开头添加一列,“A1”中的“零售商”和“A2: Last_Relevant_Cell_In_A ”中的“RetailerName”。

这是我到目前为止所做的:

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个电子表格中使用它。

1 个答案:

答案 0 :(得分: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(等)方法也是一个好主意,因此我建议您将代码更改为:

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

仅供参考

.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"

他们每个人都做同样的事情,但不同的人喜欢不同的编码风格。

相关问题