VBA – 如果列B中的某个单元格不是空白,则列A = 1
这里是我的情况:
A列是空的。 列B是客人的房间号码列C是该房间中的客人的姓名
我正在计算有多less房间被占用。 所以我把计数公式,但结果是0.我不知道为什么..
这里是代码:
Sheets("Champagne").Select Range("B2").AutoFill Destination:=Range("B2:B" & Cells(Rows.Count, 2).End(xlUp).Row) LastRow = Range("A2").End(xlDown).Row Cells(LastRow + 2, "A").Formula = "=SUM(A2:A" & LastRow & ")" LRowA = [A4200].End(xlUp).Address Range("A:A").Interior.ColorIndex = xlNone Range("A2:" & LRowA).Interior.ColorIndex = 33 Range("A:A").HorizontalAlignment = xlCenter
所以我试图把一个公式说,如果列B作为任何数字(房间号),它将在列A中计为1。然后把一个总和在列A的结尾。
这是我正在尝试的代码,但它把C列123456。
Sheets("Champagne").Select For Each Cel In Range("B2:B" & Cells(Rows.Count, 2).End(xlUp).Row) If Cel.Value <> "" Then Cel.Offset(1, 0).Value = "123456" Range("A2").AutoFill Destination:=Range("A2:A" & Cells(Rows.Count, 2).End(xlUp).Row) LastRow = Range("A2").End(xlDown).Row Next Range("B2").AutoFill Destination:=Range("B2:B" & Cells(Rows.Count, 2).End(xlUp).Row) LastRow = Range("A2").End(xlDown).Row Cells(LastRow + 2, "A").Formula = "=SUM(A2:A" & LastRow & ")" LRowA = [A4200].End(xlUp).Address Range("A:A").Interior.ColorIndex = xlNone Range("A2:" & LRowA).Interior.ColorIndex = 33 Range("A:A").HorizontalAlignment = xlCenter
如果你有第一个代码的答案,我把它也是….
要计算有多less房间(列B)被占用,我会使用如下代码:
Function CountOccupiedRooms(sheetname As String) As Long Dim j As Long dim c As Range With Worksheets(sheetname) 'Check that some data exists If IsEmpty(.Range("B2").Value) Then CountOccupiedRooms = 0 Exit Function End If For Each c In .Range("B2", .Cells(.Rows.Count, "B").End(xlUp)) If Application.WorksheetFunction.CountIf(.Range("B2:B" & c.Row), c.Value) = 1 Then j = j + 1 End If Next End With CountOccupiedRooms = j End Function
然后,假设你想把这个数字放在某个单元格中,那么这个代码可以在你的主代码中被调用
Worksheets("Summary").Range("C5").Value = CountOccupiedRooms("Champagne") Worksheets("Summary").Range("C6").Value = CountOccupiedRooms("ChocoStrawb")
目标工作表名称(“摘要”)和位置(“C5”和“C6”)只是用于说明目的 – 您可以使用任何你喜欢的东西。