Добавить динамические комментарии к ячейкам Excel через VBA

305
James

Я пытаюсь использовать комментарии, чтобы показать текущую дату выполнения задачи с помощью макроса 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 

Я ужасно осознаю, что это скорее всего неаккуратный код, но я только начинаю снова.

Решение пока работает отлично для одной ячейки. Я назвал ячейки «Target» и «Source» заранее, вместо того чтобы использовать ссылки на ячейки, такие как «B12». Теперь я хочу расширить это до нескольких ячеек, в зависимости от диапазона, который я выбираю заранее (например, A1: A6).

Выбор, куда будут добавляться комментарии, будет соответствовать диапазону одинакового размера на другом листе.

Я чувствую, что петля будет полезна, но я не знаю, с чего начать.

Картинка ниже может проиллюстрировать, что я хочу сделать. Источник заполнен динамическими датами, которые я хочу добавить в мои комментарии.

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

заранее спасибо

0
You would just need to look up how to create a range, and loop through it cell by cell. BruceWayne 5 лет назад 0
thanks batman :) Would you mind giving me a hint as to where to start? James 5 лет назад 0

1 ответ на вопрос

0
BruceWayne

Это должно начать вас. Это работает с вашей пробной фотографией, но потребуется настройка, если источник комментариев - это другой лист.

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 

enter image description here

Much obliged, Batman! :) I knew, you not only know your way around gotham! I'll give this a go! James 5 лет назад 0
Just tried this moments ago and it works wonderfully, but as you already have foreseen, I need the comment source from another worksheet. I'll be looking into that since I recon it got somethin to do with the targetRng, but If you could give me pointers again - holy VBA-Batman! :-) James 5 лет назад 0
@James where on the second worksheet are the comments, how would you find them? BruceWayne 5 лет назад 0
I amended your code with commentSrcRng = Application.InputBox("Please select the source range. This is the range that will have the source of the comments", Type:=8) James 5 лет назад 0
Я думаю, что я относительно удовлетворен нынешним подходом, большое спасибо! - Но я хотел бы внедрить еще один макрос, который просто обновляет прикрепленные комментарии, чтобы отразить последние изменения. James 5 лет назад 0

Похожие вопросы