Rtf в excel vba

The .Net Framework RichTextBox class can perform the conversion. Fortunately, this class has the ComVisibleAttribute set, so it can be used from VBA without much difficulty.

I had to create a .tlb file to Reference. In the

%SYSTEMROOT%Microsoft.NETFrameworkcurrentver

directory, run the command

regasm /codebase system.windows.forms.dll

to create the system.windows.forms.tlb file. I already had this .tlb file on my system, but I had to recreate it using this command to be able to create a .Net System.Windows.Forms RichTextBox object successfully in VBA.

With the new .tlb file created, in VBA link it to your project via Tools->References in the VBA IDE.

I wrote this test code in Access to demonstrate the solution.

Dim rtfSample As String
rtfSample = "{rtf1ansideflang1033ftnbjuc1 {fonttbl{f0 froman fcharset0 Times New Roman;}{f1 fswiss fcharset0 Segoe UI;}} {colortbl ;red255green255blue255 ;} {stylesheet{fs22cf0cb1 Normal;}{cs1cf0cb1 Default Paragraph Font;}} paperw12240paperh15840margl1440margr1440margt1440margb1440headery720footery720deftab720formshadeaendnotesaftnnrlcpgbrdrheadpgbrdrfoot sectdpgwsxn12240pghsxn15840marglsxn1440margrsxn1440margtsxn1440margbsxn1440headery720footery720sbkpagepgnstarts1pgncontpgndec plainplainf1fs22lang1033f1 hello question stemplainf1fs22par}"

Dim miracle As System_Windows_Forms.RichTextBox
Set miracle = New System_Windows_Forms.RichTextBox
With miracle
    .RTF = rtfSample 
    RTFExtractPlainText = .TEXT
End With

MsgBox RTFExtractPlainText(rtfSample)

With the result

hello question stem

I’d assume re-creating the .tlb file in the Framework64 directory would be needed on 64-bit Windows with 64-bit Office. I am running 64-bit Win10 with 32-bit Office 2013, so I had to have a 32-bit .tlb file.

 

Galina_27

Пользователь

Сообщений: 3
Регистрация: 11.03.2013

#1

11.03.2013 03:45:14

Здравствуйте.
Подскажите, пожалуйста, макрос для переноса файла в формате rtf в Excel .

Вот в этом топике

http://www.planetaexcel.ru/forum/index.php?PAGE_NAME=read&FID=8&TID=18960

я взяла макрос

мой компьютер ругается «run time error…» вроде бы на вот эту строку макроса (подсвечивает желтым).
Value = Application.Transpose(Arr)
Как поправить правильно эту строку я не знаю, поискала ещё в интернете.

Нашла вот такой макрос

Скрытый текст

Пробовала его запустить, безрезультатно.

Ещё один вопрос, макрос для rtf подойдет для txt ?
Спасибо заранее.

 

Здравствуйте, Галина.

1) Я не нашел в вашем макросе строку Value = Application.Transpose(Arr)
А ругается, скорее всего, потому, что массив Arr — пустой.
(видимо, данные не загрузились)

2) Макрос для txt, конечно, можно приспособить,
но зачем мучить Word обработкой текстовых файлов,
когда данные из файла TXT намного проще и быстрее загрузить напрямую, не запуская Word.

Вот несколько примеров макросов для чтения текстовых файлов из Excel:

http://excelvba.ru/code/txt
http://excelvba.ru/code/CSV2Excel
http://excelvba.ru/code/TextFile2Array
http://excelvba.ru/programmes/TemperaturesFromTextFile
http://excelvba.ru/programmes/Notepad

 

Galina_27

Пользователь

Сообщений: 3
Регистрация: 11.03.2013

#3

11.03.2013 08:06:48

Добрый день.
Игорь, спасибо за ответ.
Вечером попробую Ваши коды.

Честно говоря, я в VBA ничего не понимаю, с необходимостью применить макросы столкнулась буквально в прошлом месяце, подыскиваю себе понятную литературу, немного читала Гарнаева.

Насчет моих вопросов.
Вопрос №2 я немного некорректно сформулировала, имелось в виду, подойдет ли макрос, импортирующий из rtf в Excel для такой же цели для файла в формате txt (импорта txt в Excel)

Вопрос №1
Вот такой макрос я пыталась запустить, автор KuklP
‘ ZVI:2009-09-02

http://www.planetaexcel.ru/forum.php?thread_id=9631

Скрытый текст

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

#4

11.03.2013 08:29:25

Цитата
Galina_27 пишет:
автор KuklP

Вот те раз! C чего Вы взяли? Я в той теме даже не участвовал :D Автор Владимир Захаров, ZVI.

Я сам — дурнее всякого примера! …

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

Галина, можете приложить пример файла, содержимое которого нужно скопировать в Excel?

 

Добрый Вечер! У меня аналогичная проблема. Игорь,у меня не срабатывает Ваша функция по ссылке

TextFile2Array

т.е. массив arr — остаётся пустым. Т.е. не проходит разделение файла по столбцам

Изменено: SvetaS_love26.09.2015 21:46:47

 

SvetaS_love

Пользователь

Сообщений: 132
Регистрация: 14.07.2015

#7

26.09.2015 21:45:45

может быть кто-то сможет подсказать как перевести функцию

Код
Private Sub
Button1_Click(ByVal
sender As System.Object, ByVal
e As System.EventArgs)
Handles Button1.Click

        Dim Mass()

        Dim STR As String

        Mass = IO.File.ReadAllLines("D:1.csv")

        STR = Split(Mass(2), ",")(3)

        MsgBox(STR)

    End Sub

на VBA Excel
меня интересует именно строка  

Код
  Mass = IO.File.ReadAllLines("D:1.csv")

Изменено: SvetaS_love26.09.2015 21:49:42

одинокий странник

 

SvetaS_love

Пользователь

Сообщений: 132
Регистрация: 14.07.2015

#8

26.09.2015 21:52:55

т.е.   я  пишу

Код
Dim nn As Long
Dim la() As String
Dim lr() As String
Dim n As String
nn = 1
    Const ForReading = 1, ForWriting = 2, ForAppending = 3
    Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
    Dim fs, f, ts, s
    Set fs = CreateObject("Scripting.FileSystemObject")
           
   Set f = fs.GetFile("D:file.csv")
     
   Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)

но как вставить строку

Код
Mass = IO.File.ReadAllLines("D:1.csv")

одинокий странник

 

Задача описана в теме «RunTime Error 7 — Out of Memory»

 

SvetaS_love

Пользователь

Сообщений: 132
Регистрация: 14.07.2015

#10

26.09.2015 22:15:43

запись в файл происходит тут  (всё работает) , но как прочитать по столбцам в массив? Почему не срабатывает функция

TextFile2Array

c выгрузкой уже записанного ранее файла?

Код
Function txt_write_from_Mas(m As Variant, n%)
Dim i#, ii#, s$
    For i = 1 To UBound(m)
    s = m(i, 1)
        For ii = 2 To UBound(m, 2)
            s = s & vbTab & m(i, ii)
        Next
        Print #n, s '    Write #n, sf
    Next

одинокий странник

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

Ваш файл открываете в Excel, а потом выделяете столбец А с данными и применяете текст по столбцам, разделитель — знак табуляции

 
Kuzmich

, а на языке VBA ?

 

 в файле 300 000 строк. Нужно быстро на VBA…

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

Так дольше писать код VBA, чем выделить 300 000 строк и разделить по столбцам.
Вот ваш файл c разделенными данными в формате .xls

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

#15

26.09.2015 22:39:00

Цитата
Нужно быстро на VBA…

Посмотрите метод объекта Range TextToColumns

 
Kuzmich

, там задача расписана в теме «Задача описана в теме «RunTime Error 7 — Out of Memory»», а в ручную я и так каждую неделю делаю…нужен кусок кода, чтобы вставить его в другой кусок кода….. и .т.д.

 
Kuzmich

, ты вообще представляешь , что при считывании с каждой строки листа при объёме в 300 000 строк Excel  просто повиснит? Зачем ты мне файл прислал без макроса? у меня его считывать некуда….

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

#18

26.09.2015 22:46:32

Цитата
у меня его считывать некуда..

Как же вы узнали, что там нет макроса?

 

Doober

Пользователь

Сообщений: 2201
Регистрация: 09.04.2013

#19

26.09.2015 23:03:55

Цитата
Kuzmich написал:
Как же вы узнали, что там нет макроса?

OFF:На Привозе сказали

<#0>

Carrying on from this question: https://www.experts-exchange.com/questions/21413136/Convert-RTF-to-XLS-Freeware.html

I’m trying to manipulate an RTF file by inserting it’s contents into Excel.  This all works fine by copying and pasting the data, and then manually sorting the information, although there’s one slight problem.  All the data in the RTF file is stored in text boxes, some of those text boxes span over two lines, and there’s no easy way to determine which lines should be joined together.

An example:

There’s a column with surnames on each page.  by default there are 20 surnames on each page.  One page in particular has 20 surnames but one particular surname is hyphenated and spans across two lines i.e. smith-constantine.  A simple copy and paste into excel as above would work perfectly, although now I have 21 lines of surnames, and only 20 lines of firstnames.  Without manually matching them up, I’m looking for a way to somehow work out which two surname lines have to be joined together.
I tried to extend the horizontal size of the textbox manually, in the hope that maybe the lines:

smith-
constantine

would retract back to the line:

smith-constantine

but no such luck.  It’s not a word-wrap so I have to manually delete the gap between the two, then they join up successfully, but as far as a macro is concerned, I can’t see any way to do this automatically.

Any ideas?

  1. 05-19-2020, 12:47 AM


    #1

    excel_joe is offline


    Registered User


    RTF to text using VBA

    I am looking for any solution to convert RTF to plain text. I have a large project with many userforms,classes, modules. I use the file system object to read an RTF file into a string.

    I need to convert the string from RTF to plain text (or extract the plain text, perhaps with a regex?)
    I have seen the older solutions using richtextbox controls , but it has its issues with the references. I found some info about the office ContentControls class (type=wdRichTextBox), can it do the conversion/extract of the plain text?

    Thanks,
    Joe


  2. 05-19-2020, 01:54 AM


    #2

    Re: RTF to text using VBA

    I did one years ago, but I need to see your rtf file first, so that I can test it.


  3. 05-19-2020, 08:35 AM


    #3

    excel_joe is offline


    Registered User


    Re: RTF to text using VBA

    {rtf1ansiansicpg1252deff0deflang2070{fonttbl{f0fnilfcharset0 Microsoft Sans Serif;}{f1fnilfcharset0 Tahoma;}{f2fnilfcharset2 Symbol;}}
    viewkind4uc1pardf0fs17par
    pard{pntextf2’B7tab}{*pnpnlvlbltpnf2pnindent0{pntxtb’B7}}f1 onepar
    {pntextf2’B7tab}twopar
    {pntextf2’B7tab}threepar
    {pntextf2’B7tab}par
    pardfs17par
    }


  4. 05-19-2020, 08:58 AM


    #4

    Arrow Re: RTF to text using VBA

    Just obviously using Word �


  5. 05-19-2020, 12:41 PM


    #5

    Re: RTF to text using VBA

    I don’t think «System_Windows_Forms.RichTextBox» is not available now for Excel vba.

    Why not just open rtf file from Word and read the text from there?
    I can write a code using Regular Expressions, but it will be only for this particular file, not in general.


Johnny C

Johnny C

Well-known Member

Joined
Nov 7, 2006
Messages
1,069
Office Version
  1. 365
Platform
  1. Windows


  • #1

Hi

Our Admin system dumps 60+ files each night in RTF format. Someone has to go into each one and find, copy and paste assorted totals, and it takes forever, and in October that’s going to expand to circa 250 files. The Admin system can only export as RTF.

If I could somehow open the file as a txt file in Excel I could automate it for them.

Is there a way I could do this?

Cheers

Понравилась статья? Поделить с друзьями:
  • Rtf to word mac
  • Run time error 1004 vba excel application defined or object defined error
  • Rtf to excel converter online
  • Run time error 1004 excel ошибка
  • Rtf from excel online