Is there a better way to do this? VBA script

孤人 提交于 2021-02-05 12:18:00

问题


What I have here is a tracking list, for feeding pumps. We have to account for stock levels, so I made this. When you enter a pump, into the table, nothing happens. When you put a patient's name against it, the row goes pink to indicate the pump has left our stock.

I was trying to get a script/macro together that could count the pumps that we still had (i.e the white rows, e column), and display the list (table will get quite long in future) to the user.

My code:

It loops through the c column (serial numbers) for each "cll", an if statement checks if there is anything in the cell 2 columns to the right (patient name, if there is a patient name, it means the pump has been given out) AND if there is a value in the e column (serial numbers). It displays serial numbers that fulfill the criteria in a series of message boxes.

The code works, and I'm happy to roll it out, as this isn't an overly important issue, and I'll be leaving it with a group of technophobes. However, I'm wondering, it's a little clunky?

I don't like the seperate message boxes, but I can't find any info on making an array in excel VBA, and I don't like checking the IF using the offset property.

I couldn't make checking the cll.Interior.color/colorIndex work, as excel seemed to think the cells are all the same color, regardless of what color they actually are. (?conditional formatting causing issues).

Hope this makes sense,

EDIT:

Code as text:

    Private Sub CommandButton1_Click()

Dim cll As Range


For Each cll In Range("c6:c200")
If IsEmpty(cll.Offset(0, 2)) And cll.Value > 0 Then
MsgBox "Pump Serial number: " & vbNewLine & vbNewLine & cll.Value
End If


Next cll


End Sub

回答1:


  1. concatenate the serial numbers in the loop and then after the loop show the concatenated string.
  2. find the last cell with a value and only loop to that row.
  3. Iterate a variant array instead of the range, it is quicker

Private Sub CommandButton1_Click()
    Dim cll As Variant
    cll = ActiveSheet.Range("C6", ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Offset(, 2)).Value
    
    Dim str As String
    str = ""
    
    Dim delim As String
    delim = ""
    
    Dim i As Long
    For i = 1 To UBound(cll, 1)
        If Not IsEmpty(cll(i, 1)) And IsEmpty(cll(i, 3)) Then
          str = str & delim & cll(i, 1)
          If delim = "" Then delim = vbNewLine
        End If
    Next i
    
    MsgBox "Pump Serial number: " & vbNewLine & vbNewLine & str
End Sub



来源:https://stackoverflow.com/questions/63639757/is-there-a-better-way-to-do-this-vba-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!