VBA 経由で Excel セルに動的コメントを追加する

VBA 経由で Excel セルに動的コメントを追加する

私は、VBA マクロを介してコメントを使用してタスクの現在の期限を表示しようとしています。現在の解決策は次のようになります。

Sub AddDueDates()
Dim strPrefix As String
  strPrefix = ""
  With Range("Target")
If .Comment Is Nothing Then
   .AddComment
End If
.Comment.Visible = True
.Comment.Shape.TextFrame.AutoSize = True
  End With

 With Range("Target").Comment
.Text strPrefix & Range("Source").Text 
End With
End Sub

これはおそらくずさんなコードだということは重々承知していますが、私はまだやり直しを始めたばかりです。

これまでの解決策は、単一のセルに対してはうまく機能します。「B12」などのセル参照を使用する代わりに、事前にセルに「ターゲット」と「ソース」という名前を付けました。次に、事前に選択した範囲 (例: A1:A6) に応じて、これを複数のセルに拡張します。

コメントが追加される選択範囲は、別のワークシート内の同じサイズの範囲に対応します。

ループが役立つような気がしますが、どこから始めればよいかわかりません。

下の図は私がやりたいことを示しているかもしれません。ソースには、コメントに追加したい動的な日付がいっぱいです。

https://i.stack.imgur.com/EsfEa.jpg

前もって感謝します

答え1

これで開始できるはずです。これはサンプル写真では機能しますが、コメント ソースが別のワークシートである場合は調整が必要になります。

Sub AddDates()
Dim targetRng As Range, commentSrcRng As Range
Dim strPrefix As String ' why this variable? You never seem to use it

Set targetRng = Application.InputBox("Please select the target range.  This is the range that will have comments added to each cell", Type:=8)
Set commentSrcRng = targetRng.Offset(0, 3) ' from the screenshot. Will have to tweak if this is a different worksheet.

Dim cel As Range
Dim i As Long
i = 1
For Each cel In targetRng
    If cel.Comment Is Nothing Then
        cel.AddComment
    End If
    cel.Comment.Visible = True
    cel.Comment.Shape.TextFrame.AutoSize = True
    cel.Comment.Text strPrefix & commentSrcRng.Cells(i)
    i = i + 1
Next cel

End Sub

ここに画像の説明を入力してください

関連情報