Dim fso as new filesystemobject ошибка

Is there something that I need to reference? How do I use this:

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

I am getting an error because it does not recognize these objects.

Andrei Konstantinov's user avatar

asked Jul 13, 2010 at 0:00

Alex Gordon's user avatar

Alex GordonAlex Gordon

57.6k289 gold badges671 silver badges1066 bronze badges

Within Excel you need to set a reference to the VBScript run-time library.
The relevant file is usually located at \Windows\System32\scrrun.dll

  • To reference this file, load the
    Visual Basic Editor (ALT+F11)
  • Select Tools > References from the drop-down menu
  • A listbox of available references will be displayed
  • Tick the check-box next to ‘Microsoft Scripting Runtime
  • The full name and path of the scrrun.dll file will be displayed below the listbox
  • Click on the OK button.

This can also be done directly in the code if access to the VBA object model has been enabled.

Access can be enabled by ticking the check-box Trust access to the VBA project object model found at File > Options > Trust Center > Trust Center Settings > Macro Settings

VBA Macro settings

To add a reference:

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

Stephen Ostermiller's user avatar

answered Jul 13, 2010 at 10:46

Robert Mearns's user avatar

Robert MearnsRobert Mearns

11.8k3 gold badges39 silver badges42 bronze badges

3

In excel 2013 the object creation string is:

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

instead of the code in the answer above:

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

answered Jul 31, 2016 at 19:54

Stefano Spinucci's user avatar

1

These guys have excellent examples of how to use the filesystem object 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
%> 

shA.t's user avatar

shA.t

16.6k5 gold badges54 silver badges111 bronze badges

answered Jul 13, 2010 at 0:04

Gerald Ferreira's user avatar

Gerald FerreiraGerald Ferreira

1,3492 gold badges23 silver badges44 bronze badges

1

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

answered Feb 15, 2018 at 23:25

thedanotto's user avatar

thedanottothedanotto

6,9355 gold badges45 silver badges44 bronze badges

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

Stephen Ostermiller's user avatar

answered May 4, 2018 at 16:18

FIRE FOX's user avatar

Is there something that I need to reference? How do I use this:

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

I am getting an error because it does not recognize these objects.

Andrei Konstantinov's user avatar

asked Jul 13, 2010 at 0:00

Alex Gordon's user avatar

Alex GordonAlex Gordon

57.6k289 gold badges671 silver badges1066 bronze badges

Within Excel you need to set a reference to the VBScript run-time library.
The relevant file is usually located at \Windows\System32\scrrun.dll

  • To reference this file, load the
    Visual Basic Editor (ALT+F11)
  • Select Tools > References from the drop-down menu
  • A listbox of available references will be displayed
  • Tick the check-box next to ‘Microsoft Scripting Runtime
  • The full name and path of the scrrun.dll file will be displayed below the listbox
  • Click on the OK button.

This can also be done directly in the code if access to the VBA object model has been enabled.

Access can be enabled by ticking the check-box Trust access to the VBA project object model found at File > Options > Trust Center > Trust Center Settings > Macro Settings

VBA Macro settings

To add a reference:

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

Stephen Ostermiller's user avatar

answered Jul 13, 2010 at 10:46

Robert Mearns's user avatar

Robert MearnsRobert Mearns

11.8k3 gold badges39 silver badges42 bronze badges

3

In excel 2013 the object creation string is:

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

instead of the code in the answer above:

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

answered Jul 31, 2016 at 19:54

Stefano Spinucci's user avatar

1

These guys have excellent examples of how to use the filesystem object 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
%> 

shA.t's user avatar

shA.t

16.6k5 gold badges54 silver badges111 bronze badges

answered Jul 13, 2010 at 0:04

Gerald Ferreira's user avatar

Gerald FerreiraGerald Ferreira

1,3492 gold badges23 silver badges44 bronze badges

1

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

answered Feb 15, 2018 at 23:25

thedanotto's user avatar

thedanottothedanotto

6,9355 gold badges45 silver badges44 bronze badges

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

Stephen Ostermiller's user avatar

answered May 4, 2018 at 16:18

FIRE FOX's user avatar

I’m writing a VBA script for a program called «ScorBase». I’m trying to call a subroutine that creates a text file yet I»m encountering this error «506».

this is the code that I’m writhing:

    Sub emailFile()

' Declare a TextStream.
Dim stream 
'As TextStream

dim fso
Set fso = New FileSystemObject

' Create a TextStream.
Set stream = fso.CreateTextFile("C:\Users\eladt\Desktop\creatFile\Mail.txt", True)

stream.WriteLine "user Email."
stream.WriteLine "Maki"
stream.WriteLine "Nigeri"
stream.WriteLine "Sashimi"
stream.Close


End Sub

asked Mar 29, 2016 at 9:36

Elad L.'s user avatar

8

An much simpler approach without using any external references:

Sub MM_Email_To_File()

Dim FF As Integer
FF = FreeFile

'// The file will be created if it doesn't exist
Open "C:\Users\eladt\Desktop\creatFile\Mail.txt" For Output As #FF

    Print #FF, "User Email"
    Print #FF, "Maki"
    Print #FF, "Nigeri"
    Print #FF, "Sashimi"

Close #FF

End Sub

You can check out this MSDN article for more information on I/O operation in VBA.

answered Mar 29, 2016 at 11:02

SierraOscar's user avatar

SierraOscarSierraOscar

17.5k6 gold badges40 silver badges68 bronze badges

If late binding from another application works then there is an issue with the VBA environment your 3rd party application is hosting, possibly it is performing some type of sandboxing.

You don’t need any external libraries to write to a file, you can try to do it natively:

Dim hf As Integer
hf = FreeFile

Open "C:\Users\eladt\Desktop\creatFile\Mail.txt" For Output As #hf

Print #hf, "user Email."
Print #hf, "Maki"
Print #hf, "Nigeri"
Print #hf, "Sashimi"

Close #hf

answered Mar 29, 2016 at 10:59

Alex K.'s user avatar

Alex K.Alex K.

172k30 gold badges264 silver badges288 bronze badges

1

The comments under your original question seem to suggest that Microsoft Scripting Runtime is not available or not installed on your PC. This could be unintentional, but it might also be because IT administrators have limited access to that library in your environment.

Fortunately, there are a number of ways of writing a text file. You may be able to use the ADO library to write a stream..

Just add a Reference to Microsoft ActiveX Data Objects 2.8 Library and then replace your code with:

Sub emailFile()

  ' Declare an ADO Stream.
  Dim stream As ADODB.stream

  ' Create an ADO Stream.
  Set stream = New ADODB.stream
  stream.Open
  stream.Type = adTypeText
  stream.WriteText "user Email.", stWriteLine
  stream.WriteText "Maki", stWriteLine
  stream.WriteText "Nigeri", stWriteLine
  stream.WriteText "Sashimi", stWriteLine
  stream.SaveToFile "C:\Users\eladt\Desktop\creatFile\Mail.txt", adSaveCreateOverWrite
  stream.Close

End Sub

answered Mar 29, 2016 at 10:22

ThunderFrame's user avatar

ThunderFrameThunderFrame

9,3522 gold badges29 silver badges60 bronze badges

Объявление переменной типа File, FileSystemObject

Литраж

Дата: Вторник, 20.01.2015, 11:35 |
Сообщение № 1

Группа: Пользователи

Ранг: Новичок

Сообщений: 15


Репутация:

0

±

Замечаний:
0% ±


MS Office 2007

При запуске нижеследующего макроса возникает ошибка «User-defined type not defined»
Этот макрос открывает файлы из определенной папки, выбранной папки и вставляет значения, удаляет ненужные значения с правых столбцов. Ранее все работало.
Ругается на Dim aFile As File, fso As New FileSystemObject, wkb As Workbook

[vba]

Код

Sub ActPremiyFinal(ByVal Control As IRibbonControl)


Application.ScreenUpdating = False
Application.ActiveWorkbook.UpdateLinks = xlUpdateLinksNever
Application.DisplayAlerts = False
Dim aFile As File, fso As New FileSystemObject, wkb As Workbook
ПутьКПапке = GetFolderPath(«Заголовок окна», ThisWorkbook.Path) ‘ запрашиваем имя папки
If ПутьКПапке = «» Then Exit Sub ‘ выход, если пользователь отказался от выбора папки
For Each aFile In fso.getfolder(ПутьКПапке).Files
DisplayAlerts = False
If fso.GetExtensionName(aFile.Name) Like «xls*» Then
Set wkb = Workbooks.Open(aFile.Path)
UpdateLinks = 0
‘****************************************************************************************
Application.ScreenUpdating = False
Application.ActiveWorkbook.UpdateLinks = xlUpdateLinksNever
Application.DisplayAlerts = False
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns(«F:O»).Select
Selection.Delete Shift:=xlToLeft
‘*****************************************************************************************
wkb.Close SaveChanges:=True
Set wkb = Nothing
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.ActiveWorkbook.UpdateLinks = xlUpdateLinksAlways
‘заканчиваем
End Sub

[/vba]

Путь к папке берется из функции:

[vba]

Код

Function GetFolderPath(Optional ByVal Title As String = «Выберите папку», _
Optional ByVal InitialPath As String = «W:\Журавлёва\») As String
‘ функция выводит диалоговое окно выбора папки с заголовком Title,
‘ начиная обзор диска с папки InitialPath
‘ возвращает полный путь к выбранной папке, или пустую строку в случае отказа от выбора
Dim PS As String: PS = Application.PathSeparator
With Application.FileDialog(msoFileDialogFolderPicker)
If Not Right$(InitialPath, 1) = PS Then InitialPath = InitialPath & PS
.ButtonName = «Выбрать»: .Title = Title: .InitialFileName = InitialPath
If .Show <> -1 Then Exit Function
GetFolderPath = .SelectedItems(1)
If Not Right$(GetFolderPath, 1) = PS Then GetFolderPath = GetFolderPath & PS
End With
End Function

[/vba]

Господа, помогите, пожалуйста! Понять не могу в чем проблема? Уже 3 день бьюсь :'(


Проблема решена: Оказывается, что каким-то мистическим способом отключилась в references Microsoft Scripting Runtime (SCRUN.DLL). Так и думала, что проблема где-то там, но не знала как называется эта библиотека.
Всем спасибо. Тему можно закрыть. Извините.

Сообщение отредактировал ЛитражВторник, 20.01.2015, 12:05

 

Ответить

nilem

Дата: Вторник, 20.01.2015, 11:59 |
Сообщение № 2

Группа: Авторы

Ранг: Старожил

Сообщений: 1612


Репутация:

563

±

Замечаний:
0% ±


Excel 2013, 2016

посмотрите в ссылках (Tools -> References), подключена ли библ. Windows Script Host Object Model


Яндекс.Деньги 4100159601573

 

Ответить

Литраж

Дата: Вторник, 20.01.2015, 12:07 |
Сообщение № 3

Группа: Пользователи

Ранг: Новичок

Сообщений: 15


Репутация:

0

±

Замечаний:
0% ±


MS Office 2007

nilem, Спасибо, сейчас и ее подключу:)

 

Ответить

Sub Content_for_etfs_convert()
Kill "D:option programsотборIN*.*"
Kill "D:option programsотборOUT*.*"
  Dim fso
  Set fso = CreateObject("scripting.filesystemobject"):  fso.CopyFolder "C:UsersАдминистраторDownloadsStocksrcdistdownloads", "D:option programsотборIN"
 
Set fso = CreateObject("Scripting.FileSystemObject")
cPath = fso.GetParentFolderName(ThisWorkbook.FullName)
 
cPathIn = cPath & "In"
cPathOut = cPath & "Out"
 
Set Folder = fso.GetFolder(cPathIn)
For Each File In Folder.Files
   If fso.GetExtensionName(File.Name) = "txt" Then
      With fso.OpenTextFile(cPathIn & File.Name, 1, True)
         cIn = .ReadAll
         .Close
      End With
      cOut = vbCrLf & "DATE"
      arrL = Split(cIn, vbLf)
      For i = LBound(arrL) To UBound(arrL)
         If Len(arrL(i)) > 0 Then
            arrD = Split(arrL(i), ",")
            arrD(0) = Right(arrD(0), 2) & "." & Mid(arrD(0), 5, 2) & "." & Left(arrD(0), 4)
            For j = 1 To 4
               cnum = Replace(arrD(j), ".", ",")
               arrD(j) = Replace(CStr(Round(CDbl(cnum), 2)), ",", ".")
            Next
            cnum = Replace(arrD(6), ".", ",")
            arrD(6) = Replace(CStr(Round(CDbl(cnum), 0)), ",", ".")
            cOut = cOut & vbCrLf & Join(Array(arrD(0), arrD(1), arrD(2), arrD(3), arrD(4), arrD(6)), vbTab)
         End If
      Next
      With fso.OpenTextFile(cPathOut & File.Name, 2, True)
         .Write cOut
         .Close
      End With
   End If
Next

 
MsgBox "Ok"

End Sub
Sub replaceTxts()
    Dim fso As New FileSystemObject, curFolder As Folder, curFile As File
    folderPath = "D:option programsотборOUT"
    Set curFolder = fso.GetFolder(folderPath)
    For Each curFile In curFolder.Files
        If Right(curFile.Path, 4) = ".txt" Then
            curFile.copy Replace(curFile.Path, ".txt", ".csv")
            curFile.Delete
        End If
    Next curFile
End Sub

Понравилась статья? Поделить с друзьями:
  • Dim app as word application ошибка
  • Df771 ошибка рено меган 3 дизель
  • Df771 ошибка рено дастер дизель не заводится
  • Df771 ошибка к9к
  • Df770 ошибка рено