首页 > 解决方案 > Excel VBA - 为引用单元格分配地址

问题描述

我有一系列复选框单元格,该范围上方的几行自动列出相应月份的月份日期和工作日。当单击按钮时,我正在尝试用周末或本月以外的“/”填充所有框。

我已经为完全相同的标准设置了条件格式,以使复选框单元格的背景变为灰色,并且所述逻辑完美运行。我使用“+”代替 OR,WEEKDAY 中的第二个参数对应于开始的工作日(1 = 星期日)。已经尝试在 VBA 函数中使用 1 但每个单元格仍然被填充。

=OR(WEEKDAY(B$4,1)>6,WEEKDAY(B$4,1)<2)+NOT(MONTH(B$4)=MONTH($B$3)) 'Works perfect

我的“Set refcell.Column ...”行有什么问题?它给了我“错误数量的参数或无效的属性分配”编译错误。

修改后的代码:

Private Sub CommandButton1_Click()
    
    Dim rng As Range, cell As Range, refcell As Range
    
    CommandButton1.AutoSize = False
    CommandButton1.AutoSize = True
    CommandButton1.Height = 21.75
    CommandButton1.Left = 218.25
    CommandButton1.Width = 96
    
    With ThisWorkbook.ActiveSheet
        Set rng = .Range("B7:AF16")
        
        For Each cell In rng
            Set refcell = .Cells(4, cell.Column)
            
            If Weekday(refcell, vbSunday) > 6 Or Weekday(refcell, vbSunday) < 2 Or (Not (Month(refcell) = Month(B3))) Then 
            'Above logic seems to just fill every cell
                cell.Value = "/"
            End If
        Next cell
        
    End With
    
End Sub

标签: excelvba

解决方案


要设置单个单元格范围,请使用cells

代替:

        Set refcell.Column = cell.Column 'This is Read-Only
        Set refcell.Row = 4 'This is Read-Only

用这个:

With Thisworkbook.Sheets("Sheet1") ' Change accordingly
     Set rng = .Range("B7:AF16") 
     For Each cell In rng
         set refcell = .cells(4, cell.column)

作为良好的实践参考工作簿和工作表,如果你不这样做,它最终会咬你。


推荐阅读