我正在使用 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 列。我只希望从第 2 个单元格向下应用此公式,并且只应用于具有值的单元格。因此从 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