How do I use FileSystemObject in VBA?

有什么我需要参考的吗? 我如何使用这个:

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

我得到一个错误,因为它不能识别这些对象。

386643 次浏览

这些人有很好的例子说明如何使用文件系统对象 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
%>

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

  • 若要引用此文件,请加载 VisualBasic 编辑器(ALT + F11)
  • 从下拉菜单中选择 Tools > References
  • 将显示可用引用的列表框
  • 勾选「 Microsoft Scripting Runtime」旁边的核取方块
  • scrrun.dll文件的完整名称和路径将显示在列表框的下面
  • 点击 OK按钮。

如果已经启用了对 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

To remove a reference:

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

In excel 2013 the object creation string is:

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

代替上述答案中的代码:

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

添加引用之后,我必须使用

Dim fso As New Scripting.FileSystemObject

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

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