简体   繁体   English

如何使用VBA编写的自定义公式从Excel单元格中选择特定的字符串片段

[英]How can I pick specific string fragments out of an excel cell using a custom formula written in VBA

At work I am required to reformat incorrect Addresses on a weekly basis from records in our Salesforce instance. 在工作中,我需要每周从Salesforce实例中的记录重新格式化不正确的地址。 We gather the incorrectly formatted addresses using a Report and export them to an Excel file. 我们使用报告收集格式错误的地址,并将其导出到Excel文件。 My job is simply to manipulate the data in the file to format them properly then reinsert them into the database. 我的工作仅仅是操纵文件中的数据以正确格式化它们,然后将它们重新插入数据库。

Typically the addresses are formatted as so: 通常,地址的格式如下:

5 Sesame Street, Anytown, Anyplace 芝麻街5号,任何地方,任何地方

Separating these can be done easily by hand, but I typically have to work with hundreds of addresses at a time, and using default excel formulas tends to require lots of wrangling multiple cells at once to break it up into fragments. 手动将它们分开很容易,但是我通常必须一次处理数百个地址,并且使用默认的excel公式往往需要同时处理多个单元格才能将其分解为多个片段。

Thus I wrote a custom formula to run through the cell and return a specific fragment of the string based on the "Comma Number" given. 因此,我编写了一个自定义公式来遍历单元格,并根据给定的“逗号编号”返回字符串的特定片段。 So if I give a Comma Number of 1, I would get "5 Sesame Street", 2 would get me "Anytown", etc. 因此,如果我给一个逗号数字1,我​​将得到“ 5 Sesame Street”,2将得到我“ Anytown”,依此类推。

Here is my code so far: 到目前为止,这是我的代码:

 Public Function fragmentAddress(address As String, numberofcommas As Integer) As String seen = 1 lastComma = -1 Dim x As Long Dim frag As Long For x = 0 To Len(address) If Mid(address, x, 1) = "," & numberofcommas = seen Then Exit For ElseIf Mid(address, x, 1) = "," & numberofcommas <> seen Then seen = seen + 1 lastComma = x End If Next frag = Mid(address, lastComma + 1, seen - lastComma) fragmentAddress = frag 

I have not implemented the ability to handle the final value yet, but it does not give me any outputs, only outputting a "#VALUE!" 我还没有实现处理最终值的功能,但是它没有给我任何输出,仅输出“ #VALUE!”。 error when I attempt to give it the input 尝试输入时出错

 =fragmentAddress("3 Ashley Close, Charlton Kings",1) 

I have some experience with programming, but this is my first time writing anything in VBA. 我有一些编程经验,但这是我第一次用VBA编写任何东西。

Any help would be appreciated, thank you. 任何帮助,将不胜感激,谢谢。

Not exactly sure what your question is, but this is simpler: 不完全确定您的问题是什么,但这很简单:

Public Function GetAddressFragment(ByVal Address As String, ByVal Index As Integer) As String
    Dim addr() As String

    addr = Split(Address, ",")

    On Error Resume Next
    GetAddressFragment = Trim(addr(Index - 1))
End Function

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

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