简体   繁体   English

将excel公式转换为VBA宏

[英]Converting excel formula into VBA macro

I have a sheet in excel which has a lookup column for all our internal dial-code definitions.我在 excel 中有一个工作表,其中有一个用于我们所有内部拨号代码定义的查找列。 (these are in column F &G ) - I then have a lookup column where we want to match the dialcodes from our customers to find the closest match. (这些在 F & G 列中) - 然后我有一个查找列,我们希望在其中匹配来自客户的拨号代码以找到最接近的匹配项。 The formula does this right now over a series of columns by checking if there is a match, and if not then it strips out the last number and then compares again该公式现在通过检查是否存在匹配来对一系列列执行此操作,如果不匹配,则删除最后一个数字,然后再次进行比较

I then compare them to the definitions i am given然后我将它们与我给出的定义进行比较

And by removing 1 number at a time - i eventually get to a match on the codes how the sheet parses to get the match table of dial-code matches并且通过一次删除 1 个号码 - 我最终得到了代码匹配如何解析以获得拨号代码匹配的匹配

I have it in an excel formula right now but would like to make it be a VBA function i can call so it runs faster - it would need to compare all of column F and G as the match which is sorted in numerical order我现在在一个 excel 公式中使用它,但想让它成为我可以调用的 VBA 函数,以便它运行得更快 - 它需要将所有列 F 和 G 作为按数字顺序排序的匹配项进行比较

=IF($A3="","",IF(AND(F3="", CONCATENATE(C3,D3, E3,F3) = ""), IF(ISNA(VLOOKUP(LEFT($B3,MAX(0, LEN($B3) - G$1))+0,Input!$F:$G,1,FALSE))=FALSE,
VLOOKUP(LEFT($B3,MAX(0, LEN($B3) - G$1))+0,Input!$F:$G,2,FALSE),""),""))

Try尝试

Option Explicit

Sub LocateCode()

    Dim wb As Workbook, ws As Worksheet, wsInput As Worksheet
    Dim rngInput As Range, found As Range
    Dim LastRow As Long, LastInput As Long, r As Long
    Dim code As String, n As Integer
    
    Set wb = ThisWorkbook
   
    ' look up range
    Set wsInput = wb.Sheets("Input")
    With wsInput
        LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
        Set rngInput = .Range("F2:F" & LastRow)
    End With
   
    ' data
    Set ws = wb.Sheets("Input")
    With ws
       LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
       For r = 2 To LastRow
          code = .Cells(r, "B")
          n = Len(code)
          Do
              Set found = rngInput.Find(Left(code, n), Lookat:=xlWhole, LookIn:=xlValues)
              If Not found Is Nothing Then
                  .Cells(r, "C") = found.Offset(0, 1)
                  ' compare
                  If .Cells(r, "A") <> .Cells(r, "C") Then
                      .Cells(r, "A").Interior.Color = vbYellow
                  End If
                  Exit Do
              End If
              n = n - 1
              If n = 0 Then .Cells(r, "C") = "#N/A"
          Loop Until n = 0
       Next
    End With
   
    MsgBox "Done"
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM