2017-06-19 167 views
1

我在VBA中並不是很堅定,我一直在嘗試在Word中使用我之前在Excel中編寫的函數。 (如果這是工作完美!)VBA Word 2013:Scripting.FileSystemObject:運行時錯誤424 - 對象需要

的功能經過一個文本文件,並有一定的(尋求)其他字符串之後返回一個字符串:

Function keySearch(ByVal sSearch As String) As String 
Dim fso As New FileSystemObject 
Dim FileNum 
Dim DataLine As String 
Dim posOf_A As Integer 
Dim filepath As String 

keySearch = "" 

'Create filesystem object 
Set fso = CreateObject("Scripting.FileSystemObject") 

'filepath to textfile 
filepath = ActiveWorkbook.Path & "\temp.txt" 

Set FileNum = fso.OpenTextFile(filepath, 1) '<--- This is where the error occurs! 

Do While Not FileNum.AtEndOfStream 
    DataLine = FileNum.ReadLine 
    posOf_A = InStr(1, DataLine, sSearch, vbTextCompare) 
    If posOf_A = 1 Then 
     keySearch = Right(DataLine, Len(DataLine) - Len(sSearch)) 
    End If 
Loop 

FileNum.Close 

End Function 

在文本文件是線路發生錯誤應該打開。 錯誤消息:運行時錯誤424:需要對象。

我已經分裂排隊儘可能縮小從代碼通過Excel下工作完美無缺功能這個原線搜索:

FileNum = CreateObject("Scripting.FileSystemObject").OpenTextFile(ActiveWorkbook.Path & "\temp.txt", 1) 

但我似乎就是不被能夠使它工作..我已經看到了多個互聯網上的例子(看起來)完全一樣,我正在做它...

PS:Microsoft腳本運行時激活。

預先感謝任何真正讚賞的幫助!

回答

1

變化ActiveWorkbook.Path變爲ActiveDocument.Path。您正在嘗試引用文件路徑的活動Excel工作簿。

+0

就是這樣!非常感謝! – budekatude

+0

沒問題。不客氣! – Quint

相關問題