簡體   English   中英

VBA功能可遍歷單元格

[英]VBA function to iterate through cells

我正在為Excel開發VBA函數。 它將接受一個整數(我們將其稱為ref_num)和一個范圍的輸入參數。 它將搜索范圍,查找ref_num作為單元格的值。 當找到ref_num(可能存在或可能不存在)時,它將轉到ref_num所在的列的第二行,並將該值作為字符串存儲在返回變量中(該值是日期,而1- 31個都有自己的專欄)。 每次在列中找到ref_num時,第二行中的值將附加到返回字符串中。

更為具體的示例:ref_num為2,並且A,B和C列中出現2。A2,B2和C2中的值分別為1、2和3,因此該函數必須返回“ 1、2, 3" 。

這是我的偽代碼,但是我需要一些幫助來填補空白...請注意,這目前不起作用,並且該算法非常強大。 我只是想讓一些東西起作用。

Function GetDays(ref_num As Integer, range_o_cells As Range) As String
    Dim num_dates As Integer
    Dim day As String
    Set num_dates = 0

    'iterate through all the cells and see if the value is ref_num
    For Each c In range_o_cells

        If c.Value = ref_num Then
            'get the cell's column, then reference the second row and get the value. Note that this will be an int that we need to convert to a string
            'I seriously doubt the following line will work
            day = CStr(Cells(c.Column, 2).Value)

            'Once you have the value, append it to the return value
            If num_dates = 0 Then
                'This is the first value we've found, so we don't need to prepend a comma
                GetDays = day
                num_dates = 1
            Else
                'This is probably not valid VBA syntax...
                GetDays = GetDays & ", " & day
         End If

    Next c
End Function

請注意,當前,如果我這樣稱呼它: =GetDays(AG39, $P$3:$W$500)其中AG39是包含ref_num的單元格,則得到#NUM!

您的代碼中存在多個問題

  1. 您不將Set用於整數
  2. End If錯過了End If
  3. 正如您所懷疑的那樣,您對Cells的索引比較困難
  4. 您應該將返回字符串構建為day然后將其分配給函數
  5. 在范圍內循環慢
  6. 您應該聲明所有變量

更好的方法是將數據移動到變量數組,然后將其循環。 還包括傳遞給range_o_cells的范圍內的頭數據(我猜那是$P$1:$W$500

這是重構的代碼

Function GetDays( _
  ref_num As Long, _
  range_o_cells As Range, _
  Optional Sep As String = ", ") As String

    Dim dat As Variant
    Dim rw As Long, col As Long
    Dim day As String

    dat = range_o_cells.Value

    For col = 1 To UBound(dat, 2)
    For rw = 3 To UBound(dat, 1)
        If dat(rw, col) = ref_num Then
            day = day & dat(2, col) & Sep
        End If
    Next rw, col
    If Len(day) > 0 Then day = Left$(day, Len(day) - Len(Sep))
    GetDays = day
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM