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

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

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

Восстановить пароль

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

Ответ
 
Опции темы Поиск в этой теме
Старый 01.06.2011, 09:12   #11
rikomono
Пользователь
 
Регистрация: 30.05.2011
Сообщений: 10
По умолчанию

Для вот этого макроса необходимо установить связь с документом Exel.
Код:
Public Sub test()
    Dim w As Range
    Dim i As Integer
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    
    'открываем соединение к БД
    Set cn = New ADODB.Connection
    cn.ConnectionString = "тута строка подключения"
    
    'бежим по всем словам в тексте
    For i = 1 To ThisDocument.Words.Count
        'ищем слово в БД
        rs.Open cn, "select BBB from Таблица where AAA = '" + w.Text + "'"
        
        'Слово находящееся в ячейке поля "ВВВ"  справа от слова в поле "ААА" было помещено на слово в исходном тексте с помощью (PhoneticGuide
        If Not rs.EOF Then
            Set w = ThisDocument.Words.Item(i)
            If Asc(w.Text) > 30 Then w.PhoneticGuide Text:="qqq", Alignment:=wdPhoneticGuideAlignmentOneTwoOne, Raise:=14, FontSize:=10, FontName:="Lucida Sans Unicode"
        
        ' А если слова нет в базе данных, то слово в тексте заключалось  бы в такие скобки <слово>
        Else
             w.Text = "<" + w.Text + ">"
        End If
        rs.Close
    Next
    
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub
Я на сайте connectionstrings.com нашёл следующие варианты подключения к Exel 2007 (ACE OLEDB 12.0).
Для моего случая наверно надо использовать первый вариант. Подскажите как правильно это сделать. Я пробовал у меня не получилось.
Connection strings for Excel 2007 (ACE OLEDB 12.0)
Type: OLE DB Provider
Usage: Provider=Microsoft.ACE.OLEDB.12.0

Xlsx files
This one is for connecting to Excel 2007 files with the Xlsx file extension. That is the Office Open XML

format with macros disabled.

Код:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.

Treating data as text
Use this one when you want to treat all data in the file as text, overriding Excels column type

"General" to guess what type of data is in the column.

Код:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";
If you want to read the column headers into the result set (using HDR=NO even though there is a header) and

the column data is numeric, use IMEX=1 to avoid crash.

To always use IMEX=1 is a safer way to retrieve data for mixed data columns. Consider the scenario that one

Excel file might work fine cause that file's data causes the driver to guess one data type while another

file, containing other data, causes the driver to guess another data type. This can cause your app to

crash.

Xlsb files
This one is for connecting to Excel 2007 files with the Xlsb file extension. That is the Office Open XML

format saved in a binary format. I e the structure is similar but it's not saved in a text readable format

as the Xlsx files and can improve performance if the file contains a lot of data.

Код:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myBinaryExcel2007file.xlsb;Extended Properties="Excel 12.0;HDR=YES";
You can also use this connection string to connect to older 97-2003 Excel workbooks.

"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.
Xlsm files
This one is for connecting to Excel 2007 files with the Xlsm file extension. That is the Office Open XML

format with macros enabled.

Код:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsm;Extended 

Properties="Excel 12.0 Macro;HDR=YES";
Important note!
The quota " in the string needs to be escaped using your language specific escape syntax.
c#, c++ \"
VB6, VBScript ""
xml (web.config etc) &quot;
or maybe use a single quota '.

"HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.
rikomono вне форума Ответить с цитированием
Старый 01.06.2011, 12:06   #12
doober
Старожил
 
Аватар для doober
 
Регистрация: 02.05.2009
Сообщений: 3,907
По умолчанию

Зачем вам каждый раз дергать файлы базы.
Смотрите вложение.все работает как хотите
Порядок отрытия файлов тот же
Вложения
Тип файла: rar ААА.rar (18.8 Кб, 12 просмотров)
Анализ,обработка данных Недорого
doober вне форума Ответить с цитированием
Старый 01.06.2011, 19:59   #13
rikomono
Пользователь
 
Регистрация: 30.05.2011
Сообщений: 10
По умолчанию

Ура он работает, но только когда каждое слово на отдельной строке, а когда он в виде обычного текста то он не работает. Там
наверно надо внести изменения в цикле поиска слов?
Когда вот такой текст, то макрос не работает.
ААА.rar

Последний раз редактировалось rikomono; 01.06.2011 в 20:13.
rikomono вне форума Ответить с цитированием
Старый 02.06.2011, 20:49   #14
rikomono
Пользователь
 
Регистрация: 30.05.2011
Сообщений: 10
По умолчанию

doober
Посмотрите, пожалуйста, макрос +++2.rar
Я измени поиск по тексту. Макрос стал работать по другому.
Подскажите, как сделать так чтобы игнорировались пробелы и знаки препинания.
rikomono вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Запрос к базе данных на HQL fearchik Java Базы данных (JDBC, JPA, Hibernate) 0 30.04.2011 21:01
Запрос к базе данных nec117 PHP 0 09.03.2011 17:40
sql запрос к базе sashonk SQL, базы данных 8 01.09.2010 11:11
как правельно составить запрос к базе данных? не могу найти ошибку... Человек_Борща SQL, базы данных 6 27.02.2010 17:22
Запрос к базе данных Table A-1_S БД в Delphi 10 03.09.2009 21:14