2017-06-08 6 views
0

私はかなりプログラミング初心者で、さらにVBAの方が新しいです。ダイナミックセル範囲にシンプルなコンテンツを追加するVBA

「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

あなたは


(私はあなたの最後に使用セルが列Fにあったと仮定?それはあなたのコード6行する移入を説明するだろう)

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

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

を変更する必要があります

Rangeと(など)の方法をworとすることをお勧めします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]、、))...コード行に '.Find'の前に '.Cells'を追加した後に動作します。いずれにせよ、これは大きな助けとなりました!同じように動作するさまざまなバージョンのコードをレイアウトしていただければ幸いです。少し実験した後、私は後者を好むことが分かった。おそらくそれはより簡潔に感じるので、それは私だけです。再度、感謝します! –

+0

@JohnSmith - おっと - どのように恥ずかしい!誰も私の間違いに気付かないように私は答えを編集しました。 – YowE3K

+0

@ YowE3K Lol。心配ない!それは、コード内で何が起こっているのかを知っていることを私に思い出させ、自分自身に証明しました。再度、感謝します! –

関連する問題