Любимая мозоль
Автор Серж, 5 июня 2013, 09:55
0 Пользователи и 1 гость просматривают эту тему.
Друзья! Кто-нибудь встречался с ошибкой «Синтаксическая ошибка BASIC. Неожиданный символ: CRLF»?
Раньше мне приходилось часто ее видеть. Возникает после копирования кода из pdf или doc. Устраняется перенабором части кода и то не всегда.
Как я понимаю, связана с присутствием в коде какого-то непечатного символа.
Недавно опять встретил. Может кто сможет объяснить суть оного в более аргументированном виде.
Это одна строка разбита на две строки
+1
Это случается, когда длинные строки кода в угоду форматированию переносится со строки на строку. В редактор они так и вставляются — разными строками.
Нужно или символ подчеркивания добавить в конце первой строки, в качестве указания, что оператор еще не закончился, или просто разрыв строк удалить.
Кстати, это не единственная ошибка в этой серии. Если разрыв прошел по параметрам метода, можно нарваться и на сообщение вида «Синтаксическая ошибка BASIC. Неожиданный символ: ,.»
Да, действительно, возникает именно в местах, где текстовый редактор разделил одну строчку кода на две строки текста. Спасибо.
- Форум поддержки пользователей LibreOffice, Apache OpenOffice
-
►
Главная категория -
►
Basic -
►
Любимая мозоль
- Печать
Страницы: [1] Вниз
Тема: Правила BASIC не работают в макросах LibreOffice, или почему не едут лыжи? (Прочитано 9738 раз)
0 Пользователей и 1 Гость просматривают эту тему.
MAMOHT
Дорогому All-у доброго времени суток и года!
«Всё было хорошо пока не занялся программированием…»
«МАМОНТ. Copyright 11:21 29.06.2012 г.»
Как древний виндузятник порочащий весь и вся Человечную ОС по воле судьбы был приговорён к освоению софта под Линукс. И вот, при попытке написания макросов под LibreOffice, столкнулся с такими вот траблами:
При создании книжного макроса:
Sub MyCursor
Dim Doc As Object
Dim Cursor As Object
Dim sPath As String
Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Вот здесь выскакивает окно сообщения с надписью: «Свойство или метод не найдены: Text»
…..........
А здесь в сообщении чётко указана моя домашняя директория, но НЕ ТА директория в которой СЕЙЧАС открыт документ.
…........
sPath = CurDir$
MsgBox sPath
…......
End Sub
Проблема:
Из чьей кожи надо сделать бубен и какие изучить PAS, чтобы при составлении макроса на BASIC в LibreOffice 3.5.4.2 ID сборки: 350m1(Build:2) системы Ubuntu 10.04.4 всё-таки РАБОТАЛО правило Cursor = Doc.Text.createTextCursor() и как мне получить ТУ ТЕКУЩУЮ директорию в которой сейчас открыт АКТИВНЫЙ документ?
Ожидаю конкретных, корректных без словоблудства предложений по решению этих, как-бы на чей то взгляд, проблем.
Спасибо за понимание.
« Последнее редактирование: 29 Июня 2012, 15:56:47 от Чистый »
Señor_Gaga
>>Ожидаю конкретных, корректных без словоблудства предложений по решению этих, как-бы на чей то взгляд, проблем.
Если мне изменяет память — бейсик идет только для msWord.
Для ОО и LO есть свой скриптовый язык.
MAMOHT
>>Ожидаю конкретных, корректных без словоблудства предложений по решению этих, как-бы на чей то взгляд, проблем.
Если мне изменяет память — бейсик идет только для msWord.
Для ОО и LO есть свой скриптовый язык.
Вторую часть КАК-БЫ проблемы КАК-БЫ решил. Правда использованием не кратчайшего пути: это КАК-БЫ проехать в Париж через Владивосток. Нашёл описание на 114 странице книги Эндрю Питоньяк (Andrew Pitonyak)OpenOffice.org pro. Автоматизация работы.
Теперь к Señor_Gaga. Здесь точно КТО-ТО ошибается!!!
Переписываю дословно окно сообщения:
«Ошибка времени выполнения BASIC.
Свойство или метод не найдены: TEXT»
brij
Не могу сейчас точно ответить на Ваш вопрос, но просто вспомнил, что у Питоньяка есть много чего по макросам ЛО. Наверняка, Вам уже это известно, но все же на всякий пожарный Если дружите с английским, то здесь http://www.pitonyak.org/oo.php/ можно найти очень много полезного, особенно мне когда-то сильно помог его «Macro document» http://www.pitonyak.org/oo.php/AndrewMacro.pdf. Там кстати, есть и его еще незаконченный список параллелей с VBA. Может пригодится.
Dixi257
- Печать
Страницы: [1] Вверх
Версия: 5.3.1.2
ID сборки: e80a0e0fd1875e1696614d24c32df0f95f03deb2
Потоков ЦП: 4; Версия ОС: Windows 6.1; Отрисовка ИП: по умолчанию; Способ разметки: новый;
Локаль: ru-RU (ru_RU); Calc: group
Обновил офис. Теперь ничего не работает: принажатии на кнопки выскакивает окно ошибки бейсика
Например, кнопка расстановка ударений — «Синтаксическая ошибка BASIC.
Expected: ).»
В функции AutoCode:
‘ сохраняем списки
With oACDlg.Model
Dim aArrayPS() As String : aArrayPS = .ParaStyleFindListBox.StringItemList
SaveArray( aArrayPS(), getOOoFBToolsSettingsDir() & sConstWorkParaStyle
Dim aArrayPF() As String : aArrayPF = .ParaFontFindListBox.StringItemList
SaveArray( aArrayPF(), getOOoFBToolsSettingsDir() & sConstWorkParaFont
Dim aArrayCS() As String : aArrayCS = .CharStyleFindListBox.StringItemList
SaveArray( aArrayCS(), getOOoFBToolsSettingsDir() & sConstWorkCharStyle
Dim aArrayCF() As String : aArrayCF = .CharFontFindListBox.StringItemList
SaveArray( aArrayCF(), getOOoFBToolsSettingsDir() & sConstWorkCharFont
End With
На вид и правда скобочек не хватает. И так почти на многих кнопках.
I am using this macro on excel which runs no problems. However in Libreoffice it fails. and I get Basic Syntax error. Can anyone offer advice why it will not work?
Code: Select all
Rem Attribute VBA_ModuleType=VBAModule
Option VBASupport 1
Option Explicit
''/////////////////////////////////////////////////////////////////
''// 3rd August 2010 //
''// Created by Vog
''/////////////////////////////////////////////////////////////////
#If VBA7 Then
Public Declare PtrSafe Function GetActiveWindow Lib "user32" () As Long
Public Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" ( _
ByVal hWnd1 As LongPtr, _
ByVal hWnd2 As LongPtr, _
ByVal lpsz1 As String, _
ByVal lpsz2 As String) _
As LongPtr
Public Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As LongPtr, _
ByVal wMsg As Long, _
ByVal wParam As LongPtr, _
lParam As Any) _
As LongPtr
Public Declare PtrSafe Function SetTimer Lib "user32" ( _
ByVal hwnd As LongPtr, _
ByVal nIDEvent As LongPtr, _
ByVal uElapse As Long, _
ByVal lpTimerFunc As LongPtr) _
As LongPtr
Public Declare PtrSafe Function KillTimer Lib "user32" ( _
ByVal hwnd As LongPtr, _
ByVal nIDEvent As LongPtr) _
As Long
Public Declare PtrSafe Function GetForegroundWindow Lib "user32" () As LongPtr
#Else
Public Declare Function GetActiveWindow Lib "user32" () As Long
Public Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" ( _
ByVal hWnd1 As Long, _
ByVal hWnd2 As Long, _
ByVal lpsz1 As String, _
ByVal lpsz2 As String) _
As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
lParam As Any) _
As Long
Public Declare Function SetTimer Lib "user32" ( _
ByVal hwnd As Long, _
ByVal nIDEvent As Long, _
ByVal uElapse As Long, _
ByVal lpTimerFunc As Long) _
As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal hwnd As Long, _
ByVal nIDEvent As Long) _
As Long
Public Declare Function GetForegroundWindow Lib "user32" () As Long
#End If
Private Const EM_SETPASSWORDCHAR = &HCC
#If VBA7 Then
Private Const nIDE As LongPtr = &H100
Private hdlEditBox As LongPtr
Private Fgrndhdl As LongPtr
#Else
Private Const nIDE As Long = &H100
Private hdlEditBox As Long
Private Fgrndhdl As Long
#End If
#If VBA7 Then
Public Function TimerFunc( _
ByVal hwnd As LongPtr, _
ByVal wMsg As Long, _
ByVal nEvent As LongPtr, _
ByVal nSecs As Long) As Long
Dim hdlwndAct As LongPtr
#Else
Public Function TimerFunc( _
ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal nEvent As Long, _
ByVal nSecs As Long) As Long
Dim hdlwndAct As Long
#End If
'// Do we have a handle to the EditBox
If hdlEditBox > 0 Then Exit Function
'// Get the handle to the ActiveWindow
hdlwndAct = GetActiveWindow()
'// Get the Editbox handle
hdlEditBox = FindWindowEx(hdlwndAct, 0, "Edit", "")
'// Set the password character for the InputBox
SendMessage hdlEditBox, EM_SETPASSWORDCHAR, Asc("*"), ByVal 0
End Function
Public Function InPutBoxPwd(fPrompt As String, _
Optional fTitle As String, _
Optional fDefault As String, _
Optional fXpos As Long, _
Optional fYpos As Long, _
Optional fHelpfile As String, _
Optional fContext As Long) As String
Dim sInput As String
'// Initialize
hdlEditBox = 0
Fgrndhdl = GetForegroundWindow
'// Windows-Timer
SetTimer Fgrndhdl, nIDE, 100, AddressOf TimerFunc
'// Main InputBox
If fXpos Then
sInput = InputBox(fPrompt, fTitle, fDefault, fXpos, fYpos, fHelpfile, fContext)
Else
sInput = InputBox(fPrompt, fTitle, fDefault, , , fHelpfile, fContext)
End If
'//
KillTimer Fgrndhdl, nIDE
'// Pass result
InPutBoxPwd = sInput
End Function
Sub Clearrange(sRange As String, sWorksheet As String)
Worksheets(sWorksheet).Range(sRange).ClearContents
End Sub
Sub ClearHouse1(sWorksheet As String)
' if the layout of the sheet changes,
' add or edit the ranges here for the new layout
Clearrange ("A6:A1077"), sWorksheet 'Date
Clearrange ("B6:B1077"), sWorksheet 'Quantity
Clearrange ("C6:C1077"), sWorksheet 'Name
Clearrange ("D6:D1077"), sWorksheet 'Code
Clearrange ("F6:F1077"), sWorksheet 'Serial Number
Clearrange ("I6:I1077"), sWorksheet 'Delivery Cost
Clearrange ("L6:L1077"), sWorksheet 'Invoice Number
Clearrange ("O6:Q1077"), sWorksheet 'Ebay Selling Price, Postage Customer Paids & Postage I Paid
End Sub
Sub ClearHouserent1()
Const ok As String = "jib"
Dim pw As String
pw = InPutBoxPwd("Are you sure you want to clear this sheet") '<<<<<<<<<<<<<<<<<<<<<< Changed line
If pw <> ok Then
MsgBox "Wrong password"
Exit Sub
End If
Call ClearHouse1("Calculator")
End Sub
I'm working a lot with Calc macros in LibreOffice BASIC, and this is something I didn't have before. When I program in LibreOffice BASIC, I usually save often, or set Autosave to a small interval. In past LibreOffice versions, saving didn't trigger BASIC checking, it would just save the current state. In version I'm using now, every save (manual or automatic) triggers BASIC check, and if there is an error, a dialog with "BASIC Syntax Error" is displayed. If I click on OK (the only button), the dialog just re-appears with the same error and it is not possible to do anything else than to kill LibreOffice, which means that I lose all my work. This happened to me several times while in the middle of coding something, when Autosave is triggered. Unfinished code generates Syntax error, this in turn generates endless dialogs and all I was working on was lost. Please, disable BASIC cheking when saving, I cannot develop anything with this, it constantly destroys everything I'm writing (because I must kill LibreOffice). I know that I can disable macros when opening document, but debugging this way (open document with macros disabled, edit macros, save document, close document, open document again with macros enabled, test, close document, open document with macros disabled, ...) is tiresome. I don't know if this is a "blocker" category generally, but for sure is a blocker if someone is programming in LibreOffice BASIC.
Hi Zarko, (In reply to Zarko Zivanov from comment #0) > In past LibreOffice versions, saving didn't trigger BASIC checking, it would > just save the current state. In version I'm using now, every save (manual or > automatic) triggers BASIC check, ... I think I've seen that change too, but I think already quite some time?? What is your 'reference version' > I don't know if this is a "blocker" category generally, but for sure is a > blocker if someone is programming in LibreOffice BASIC. It does not block me, but if you're doing piles of just rough stuff that has lots of errors, it will be annoying indeed.. Thanks, Cor
> I think I've seen that change too, but I think already quite some time?? > What is your 'reference version' Sorry, I don't know, it was about a year ago. > > I don't know if this is a "blocker" category generally, but for sure is a > > blocker if someone is programming in LibreOffice BASIC. > > It does not block me, but if you're doing piles of just rough stuff that has > lots of errors, it will be annoying indeed.. OK, maybe I was unclear in my bug repport, sorry. You don't need a lots of errors, just one. As I said, if I save (or autosave starts) in the middle of coding, when I just didn't finish all the structures (or if I forgot something as simple as End If), my whole work is lost (since the last successful save), no way to save it, no way to copy it somwhere else, nothing. Recovery after that won't work because saving recovery copy triggers the same behaviour. I'm really not a sloppy programmer, I'm using Calc and its BASIC for work at faculty for 6-7 years, I even contributed to Andrew Pitonyak's macro collection. I just don't understand the logic behind BASIC check while saving. If I'm in the middle of writing some code, when it is still unfinished, it MUST contain syntax errors, until all the structures are written. My instinct is to save often, even unfinished code, and I don't expect that saving my code trigers behaviour that effectively destroys it. The main problem is that "BASIC syntax error" dialog keeps poping up endlessly. It would be OK if LO just checks once, lets me know that there were errors, and saves the current work. I hope that I have explained the problem more accurately.
OK, I tried this on a new calc document, wrote a simple unfinished code and it reports the error just once and saves it. What could be the problem in my document? Why it would keep displaying error dialog endlessly? Do you maybe know what to check?
(In reply to Zarko Zivanov from comment #3)
> OK, I tried this on a new calc document, wrote a simple unfinished code and
> it reports the error just once and saves it. What could be the problem in my
> document? Why it would keep displaying error dialog endlessly? Do you maybe
> know what to check?
Sounds like an event with a macro? But then still, it would end after 6-10 messages? I wouldn't have another idea. Sorry.
Cor
On pc Debian x86-64 with master sources updated today, I don't reproduce this. For example, I typed this nonsense in a Basic macro: Sub Main print "4";t=; print '5";a End Sub I could save it without error messages. I tried also the same thing on LO Debian package 4.3.3, no problem too.
I have the same problem, and it only occurs if I use a macro with a syntax error in a formula for conditional formatting of cells. Then, when saving the document, the error dialog pops ups in a seemingly endless loop (I assume once for each cell with an invalid formula). If I remove the formulas for conditional formatting the error dialog does not appear.
(In reply to stefan.fiedler from comment #6) I forgot to mention I am using LibreOffice 3.5.4.2 on Debian Linux 7.8 x86.
(In reply to stefan.fiedler from comment #7)
> (In reply to stefan.fiedler from comment #6)
>
> I forgot to mention I am using LibreOffice 3.5.4.2 on Debian Linux 7.8 x86.
3.5.4 is old. Please try with a recent LO version, 4.4.1 and 4.3.6 have been released.
If you use Debian packages with stable repo, you can use 4.3.3 from testing repo.
Declaring a bug on a obsolete version is useless.
Can someone tell me, is it possible to debug something like this, and if it is, how? I'd really like to find what is going on.
I still haven't managed to try my document on latest LO, but I tried it with LO version 3 (that comes with Ubuntu 12.04) and it worked as expected, no endless dialog messages.
Dropping Severity -> critical (we've deprecated the 'blocker' value)
https://wiki.documentfoundation.org/QA/Bugzilla/Fields/Severity#Severity_Levels
(In reply to Zarko Zivanov from comment #11)
> I still haven't managed to try my document on latest LO, but I tried it with
> LO version 3 (that comes with Ubuntu 12.04) and it worked as expected, no
> endless dialog messages.
I believe Ubuntu 12.04 comes with LibreOffice 3.5.7. That's still a pretty old version, but at least it's working there, so I'm going to mark this as RESOLVED WORKSFORME, as it sounds like there's a version of LibreOffice available that fixes the data loss.
|