编译由字符串解析器中的vba'Left'trim函数引起的错误

时间:2015-06-17 15:32:18

标签: excel vba excel-vba

我试图创建一个vba函数来逐行解析文本字符串到excel表中。我希望该函数只打印每行中两个字符之间的子字符串。例如,html标签。在调试时,Right()函数执行我想要的操作。但Left()函数甚至不会编译。错误消息是非常小的帮助,“无效的过程调用或参数”。到底是怎么回事?我根本没有更改那行代码而且它只是工作。

解释我想要完成什么,让我说我正在解析HTML文本。我想只在“<”中查看文字和“>”标签。但我也试图编写它,所以我可以使用它来解析任意两个所需字符之间的子串。

所以这样的文字:

<html>
  <head>
  </head>
  <body>
  </body>
</html>

将打印:

html
head
/head
body
/body
/html

这只是工作。不知道为什么我收到这个错误。仅适用于Left()修剪。

Sub ParseTextFromFile()
Dim myFileName As String
Dim myLine As String
Dim FileNum As Long
Dim n As Integer
n = 1

myFileName = "C:\Users\user\Desktop\myfile.TXT"
FileNum = FreeFile
Close FileNum
Open myFileName For Input As FileNum
Do While Not EOF(FileNum)
    Line Input #FileNum, myLine
    'Debug.Print TrimString(CStr(myLine))
    Cells(n, 1).Value = TrimString(CStr(myLine))
    n = n + 1
Loop

MsgBox "" & n - 1 & " items added."
End Sub

'parses a string between two chars/string key values
Function TrimString(s As String) As String
    Dim indexOfKey As Integer
    Dim firstTrim As String
    Dim secondTrim As String
    Dim textLength As Integer
    Dim key1 As String
    Dim key2 As String
    firstTrim = ""
    secondTrim = ""

    key1 = CStr(Cells(5, 8)) 'H5 = "<"
    key2 = CStr(Cells(6, 8)) 'H6 = ">"

    'remove everything to the left of the first appearance of the key char/string
    indexOfKey = InStr(1, s, key1)
    firstTrim = Right(s, Len(s) - indexOfKey)

    'remove everything to the right of the second appearance of the key char/string
    indexOfKey = InStr(1, firstTrim, key2)
    secondTrim = Left(firstTrim, indexOfKey - 1) 'this line is throwing the error

    TrimString = secondTrim
End Function

0 个答案:

没有答案