透過 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

在此輸入影像描述

相關內容