我正在寻找编写VBA脚本来将单个Excel单元格分隔为多个单元格

我有一长串的出版物,所有的数据放在一个单元格中。 我想将每个单元格中的数据分成不同的列。 一个作者,标题,年份,期刊,date等

例如,在一个单元格中我有:

Plant RA,Page JP,Bonham JH,Jones JP Stairway to Heaven(1971)Led Zepplin Dec 5; 1(39):14802-14084

以代表作者的名字代表作者的名字,代表标题的阶梯(1971年),以Zepplin为期刊的名字,12月5日为date,1(39)为问题,以及14802-14804date。

尽pipe每篇引文在长度和作者数量等方面都会有所不同,但有可能使这一过程自动化吗? 对于一些基于像LEFT(B1,SEARCH(" ",B1)-1)这样的命令的variables来说,有太多的variables,但我不禁觉得这是一个人们经常碰到的问题。 简单的解决scheme甚至可能吗?

提前致谢。

那么,这取决于你的引用格式有多么糟糕,但是一个非常有用的自动处理复杂string的工具是正则expression式 。 以下是一些代码,演示了如何构build一个可能的解决scheme。 “Test()”子程序将演示该过程。

MSDN正则expression式快速参考

 Sub Test() Dim s(1 To 3) As String 'Format A s(1) = "Plant RA, Page JP, Bonham JH, Jones JP Stairway to Heaven (1971) Led Zepplin Dec 5;1(39):14802-14084" 'Format B s(2) = "Plant RA, Page JP, Bonham JH, Jones JP Stairway to Heaven [1971] Led Zepplin Dec 5;1(39):14802-14084" 'Unknown Format s(3) = "Plant RA, Page JP, Bonham JH, Jones JP Stairway to Heaven (1971) Led Zepplin Dec 5-1(39):14802-14084" test_string = s(1) MsgBox GetFormat(test_string) & Chr(10) & GetYear(test_string) End Sub Function GetYear(ByVal s As String) Dim YearPattern As Object Set YearPattern = CreateObject("Scripting.Dictionary") YearPattern.Add "FormatA", "\(\d{4}\)" YearPattern.Add "FormatB", "\[\d{4}\]" F = GetFormat(s) If F = "Unknown Format" Then GetYear = "Error: Format not recognized" Else Set Result = FindPattern(s, YearPattern(F)) n = Result.Count If n = 0 Then GetYear = "![No Result]" ElseIf n = 1 Then GetYear = Result(0) Else GetYear = "![Multiple results]: " For Each r In Result GetYear = GetYear & ", " & r Next End If GetYear = Clean(GetYear, CType) End If End Function Function GetFormat(ByVal s As String) Set FormatPatterns = CreateObject("Scripting.Dictionary") FormatPatterns.Add "FormatA", ",+.*\(\d{4}\).*;.*\):" FormatPatterns.Add "FormatB", ",+.*\[\d{4}\].*;.*\):" If FindPattern(s, FormatPatterns("FormatA")).Count > 0 Then GetFormat = "FormatA" ElseIf FindPattern(s, FormatPatterns("FormatB")).Count > 0 Then GetFormat = "FormatB" Else GetFormat = "Unknown Format" End If End Function Function FindPattern(ByVal s As String, ByVal p As String) As Variant 'Argument 1: The string to execute regular expressions on (s) 'Argument 2: A pattern string to execute (p) 'Return Value: An array of regular expression results Set r = CreateObject("vbscript.regexp") r.Global = True r.IgnoreCase = True r.MultiLine = True r.Pattern = p Set FindPattern = r.Execute(s) End Function Function Clean(ByVal s As String, Optional ByVal CType As String) As String 'Removes unwanted characters from a string (s) 'Based on the specified type of string "CType" Select Case CType Case "Year" Clean = Replace(Replace(Replace(s, "(", ""), ")", ""), ": ,", ": ") Case Else Clean = Replace(s, ": ,", ": ") End Select End Function