用字符串替换数组中的数字

时间:2021-02-10 02:14:44

标签: excel vba

我有这个 VBA 函数,它从另一个工作簿中提取信息并将字符串的最后五个实例的列号发回,然后将其作为数组输出并显示在五个单独的列中。我想添加一个函数,它接受每个数组值(可以是任何数字 1-10),并根据它是什么数字,用一个字符串替换它。所以,如果该列是 1,我想发回一个像“placement 1”这样的字符串。我尝试使用替换函数创建一个函数,但我无法弄清楚。任何帮助解决这个问题都会很棒。

基本上我需要的是一个函数,它可以根据数字是什么,有条件地用字符串替换数组中的数字。

这是输出数字数组的函数的代码

Option Explicit

Function find_last_5(ByVal employee_name As String, ByRef placement_data As Range)

Const number_placements_required = 5
' return array
Dim placements() As Variant
'redim to required size (1 row by 5 columns)
  ReDim placements(0, number_placements_required - 1)
 Dim i As Long
' initialise return array to #n/a
 For i = 0 To number_placements_required - 1
   placements(0, i) = CVErr(xlErrNA)
 Next i

  i = 0
  Dim first_found As String
   Dim found As Range

  With placement_data
'search passed array, backwards looking along rows from last/bottom row cell towards the top left
  Set found = .Find(what:=employee_name, _
    after:=placement_data.Range("a1"), _
    LookIn:=xlValues, _
    SearchDirection:=xlPrevious, _
    SearchOrder:=xlByRows)
  
  If Not found Is Nothing Then
      first_found = found.Address
      Do
          placements(0, i) = found.Column
          Set found = .Find(what:=employee_name, _
            after:=found, _
            LookIn:=xlValues, _
            SearchDirection:=xlPrevious, _
            SearchOrder:=xlByRows)
          i = i + 1
          
' do until 5 found or nothing found or we wrap back to first address found
      Loop While i < number_placements_required And _
      Not found Is Nothing _
      And found.Address <> first_found
    End If
 End With

 find_last_5 = placements

End Function

0 个答案:

没有答案
相关问题