我正在使用 vba 並成功應用以下程式碼,將「A」新增至每列(X、AK、AW)值中的儲存格。
ActiveSheet.Range("X2:X24").Select
For Each X In Selection
If X.Value <> "" Then X.Value = X.Value & "A"
Next
ActiveSheet.Range("AK2:AK24").Select
For Each AK In Selection
If AK.Value <> "" Then AK.Value = AK.Value & "A"
Next
ActiveSheet.Range("AW2:AW24").Select
For Each AW In Selection
If AW.Value <> "" Then AW.Value = AW.Value & "A"
但是,我現在嘗試將以下公式應用於 Y、Z、AA 和 AB 列。我只希望這從第二個單元格向下應用,並且僅適用於有價值的單元格。所以從 Y2 開始,除非單元格為空。我似乎無法讓它發揮作用!
=TODAY()-1
=TEXT(TODAY(),"YYYYMM")
=TEXT(TODAY(),"MMM YYYY")
答案1
這將動態確定最後使用的行,其資料位於 Y 列中
將範圍 A2:BA+lastRow 複製到數組,循環每一行,並為每列分配每個公式(如果單元格不為空)。然後將數組放回範圍內
Option Explicit
Public Sub SetFormulasToNonEmptyCells()
Dim ur As Range, arr As Variant, r As Long
'The selected columns start at A (col 1) to BA (col 53)
Set ur = Sheet1.Range("A2:BA" & Sheet1.Cells(Sheet1.Rows.Count, "Y").End(xlUp).Row)
arr = ur
For r = 1 To UBound(arr)
If Len(Trim$(arr(r, 10))) > 0 Then arr(r, 10) = "=TODAY()-1" 'J (10)
If Len(Trim$(arr(r, 22))) > 0 Then arr(r, 22) = "-1" 'V (22)
If Len(Trim$(arr(r, 25))) > 0 Then arr(r, 25) = "1" 'Y (25)
If Len(Trim$(arr(r, 26))) > 0 Then arr(r, 26) = "1" 'X (26)
If Len(Trim$(arr(r, 27))) > 0 Then arr(r, 27) = "=TEXT(TODAY(),""YYYYMM"")" 'AA (27)
If Len(Trim$(arr(r, 28))) > 0 Then arr(r, 28) = "=TEXT(TODAY(),""MMM YYYY"")" 'AB (28)
If Len(Trim$(arr(r, 46))) > 0 Then arr(r, 46) = "-1" 'AT (46)
Next
ur.Formula = arr
ur.Columns(4).NumberFormat = "mmm yyyy" 'Use col #'s instead of letters
End Sub