如何在VBA中使用FileSystemObject?

时间:2010-07-13 00:00:13

标签: excel vba filesystemobject

我需要参考哪些内容?我该如何使用它:

Dim fso As New FileSystemObject
Dim fld As Folder
Dim ts As TextStream

我收到错误,因为它无法识别这些对象。

5 个答案:

答案 0 :(得分:167)

在Excel中,您需要设置对VB脚本运行时库的引用。 相关文件通常位于\Windows\System32\scrrun.dll

  • 要引用此文件,请加载 Visual Basic编辑器( ALT + F11
  • 选择工具>下拉菜单中的参考文献
  • 将显示可用参考的列表框
  • 勾选“Microsoft Scripting Runtime
  • 旁边的复选框
  • scrrun.dll文件的全名和路径将显示在列表框
  • 下方
  • 点击确定按钮。

如果已启用对VBA对象模型的访问,也可以直接在代码中完成此操作。

通过勾选在文件>处找到的复选框Trust access to the VBA project object model,可以启用访问权限。选项>信托中心>信任中心设置>宏设置

VBA Macro settings

添加参考:

Sub Add_Reference()

    Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference

End Sub

删除引用:

Sub Remove_Reference()

Dim oReference As Object

    Set oReference = Application.VBE.ActiveVBProject.References.Item("Scripting")

    Application.VBE.ActiveVBProject.References.Remove oReference
'Remove a reference

End Sub

答案 1 :(得分:12)

这些人有很好的例子来说明如何使用文件系统对象http://www.w3schools.com/asp/asp_ref_filesystem.asp

<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%> 

答案 2 :(得分:11)

在excel 2013中,对象创建字符串为:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

而不是上面答案中的代码:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

答案 3 :(得分:1)

添加引用后,我不得不使用

Dim fso As New Scripting.FileSystemObject

答案 4 :(得分:1)

如上所述导入脚本运行时后,您必须进行一些轻微修改才能使其在Excel 2010(我的版本)中运行。在下面的代码中,我还添加了用户选择文件的代码。

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...
Loop

fsoStream.Close
Set FSO = Nothing

希望有所帮助!

祝你好运

的Fabio