簡體   English   中英

向動態單元格范圍VBA添加簡單內容

[英]Adding Simple Content to Dynamic Cell Range VBA

我對編程非常陌生,甚至對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個電子表格中使用它。

你應該改變

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 (etc)方法也是一個好主意,因此我建議將代碼更改為:

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"

他們每個人都能達成相同的目標,但是不同的人更喜歡不同的編碼風格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM