Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Microsoft Office и VBA программирование > Microsoft Office Excel
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 03.07.2009, 19:27   #1
ru3000
Форумчанин
 
Регистрация: 19.06.2009
Сообщений: 163
По умолчанию Как создать из excel файл txt?

Нужно макросом создать файл test.txt с относительным путем, т.е. там же, где лежит и сам файл excel. И сохранить внутри test.txt текст, например: "бла-бла-бла текст из ячейки A1 бла-бла-бла текст из ячейки A2".
ru3000 вне форума Ответить с цитированием
Старый 04.07.2009, 02:28   #2
С.М.С
Участник клуба
 
Аватар для С.М.С
 
Регистрация: 29.12.2008
Сообщений: 1,598
По умолчанию

pute = ThisWorkbook.Path
transkr = Cells(1, 1)
Open pute & "\text.txt" For Append As #1 'если файла нет, то
'создаётся новый файл, если файл существует, то значение ячейки А1 'записывается в конец документа.
Print #1, Format$(transkr)
Close #1
С.М.С вне форума Ответить с цитированием
Старый 05.07.2009, 01:28   #3
tolikman
Форумчанин
 
Регистрация: 25.08.2008
Сообщений: 159
По умолчанию

Цитата из справки самого Excel
Цитата:
Enables input/output (I/O) to a file.

Syntax

Код:
Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]
The Open statement syntax has these parts:

Part Description
pathname Required. String expression that specifies a file name — may include directory or folder, and drive.
mode Required. Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.
access Optional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.
lock Optional. Keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.
filenumber Required. A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.
reclength Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.


Important In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.


Example
This example illustrates various uses of the Open statement to enable input and output to a file.

The following code opens the file

Код:
TESTFILE
in sequential-input mode.

Код:
Open "TESTFILE" For Input As #1
' Close before reopening in another mode.
Close #1
This example opens the file in Binary mode for writing operations only.

Код:
Open "TESTFILE" For Binary Access Write As #1
' Close before reopening in another mode.
Close #1
The following example opens the file in Random mode. The file contains records of the user-defined type

Record

.

Код:
Type Record    ' Define user-defined type.
    ID As Integer
    Name As String * 20
End Type

Dim MyRecord As Record    ' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Close before reopening in another mode.
Close #1
This code example opens the file for sequential output; any process can read or write to file.

Код:
Open "TESTFILE" For Output Shared As #1
' Close before reopening in another mode.
Close #1
This code example opens the file in Binary mode for reading; other processes can't read file.

Код:
Open "TESTFILE" For Binary Access Read Lock Read As #1
tolikman вне форума Ответить с цитированием
Старый 05.07.2009, 13:58   #4
ru3000
Форумчанин
 
Регистрация: 19.06.2009
Сообщений: 163
По умолчанию

Спасибо большое. Только вот у меня не получается всавить сразу два вида тескта: "Мой текст" и Cells(1, 1). Как правильно написать эти вставки после transkr =, чтобы вставлялось одной строкой и в итоге получилось бы: "Мой текст Cells(1, 1)"?

Последний раз редактировалось ru3000; 05.07.2009 в 14:02.
ru3000 вне форума Ответить с цитированием
Старый 05.07.2009, 14:05   #5
ru3000
Форумчанин
 
Регистрация: 19.06.2009
Сообщений: 163
По умолчанию

Все, сам нашел!
transkr = "Мой текст" & Cells(1, 1)
ru3000 вне форума Ответить с цитированием
Старый 20.05.2016, 10:33   #6
denis402
Новичок
Джуниор
 
Регистрация: 20.05.2016
Сообщений: 1
По умолчанию

Друзья,изменил вышеприведенный макрос для создания файла куда будут присаться значения из первой ячейки,второй ,третьей и четвертой (первый столбец).Все работает как надо,но проблема в том,что теоретически ячеек с данными в первом столбце может быть сотня,как его видоизменить макрос дабы они брал все заполненые ячейки первого столбца?

Sub Macro()

Dim path As String
Dim ext As String
ext = "txt"
path = ThisWorkbook.path
Kill path & "\text.txt"
pute = ThisWorkbook.path
transfer1 = Cells(1, 1)
Open pute & "\text.txt" For Append As #1Print #1, Format(transfer1)
Close #1
transfer1 = Cells(2, 1)
Open pute & "\text.txt" For Append As #2
Print #2, Format(transfer1)
Close #2
transfer1 = Cells(3, 1)
Open pute & "\text.txt" For Append As #3
Print #3, Format(transfer1)
Close #3
transfer1 = Cells(4, 1)
Open pute & "\text.txt" For Append As #4
Print #4, Format(transfer1)
Close #4
denis402 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
как открыть файл.txt Sergeu Общие вопросы Delphi 1 25.09.2008 13:24
Как создать новый файл Word из макроса Excel? Dorvir Microsoft Office Excel 12 08.07.2008 16:50
Как создать txt файл Titan123 Общие вопросы Delphi 7 29.06.2008 16:56
как сохранить строчки в TXT файл Ярослав Помощь студентам 2 17.05.2008 18:43
Как прочесть txt файл www.site.ru/info.txt BR17UY Работа с сетью в Delphi 1 16.04.2007 13:01