2017-06-08 105 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。別擔心!它讓我思考並向自己證明,我知道代碼中發生了什麼。再次感謝! –

相關問題