Line number or label or statement or end of statement ошибка

I know this is probably a simply answered question, but I've search and tried multiple things, but I continue to receive errors in VBA.
  • Remove From My Forums
  • Question

  • I know this is probably a simply answered question, but I’ve search and tried multiple things, but I continue to receive errors in VBA.

    I would like to break the following statement into multiple lines:

    ActiveCell.Formula = «=IF(RC[-24]=»»Bill»»,ROUNDUP(RC[-1]/2,0),(IF(RC[-24]=»»eBill»»,ROUNDUP(RC[-1]/1,0),0))»

    I would like to break it up into two lines as follows:

    ActiveCell.Formula = «=IF(RC[-24]=»»Bill»»,ROUNDUP(RC[-1]/2,0),

       (IF(RC[-24]=»»eBill»»,ROUNDUP(RC[-1]/1,0),0))»

    I have tried multiple combinations of ampersands and underscores, but nothing has been successful.

    Any help would be greatly appreciated.

    Thanks!

Answers

  • Thanks Hans.  I believe I tried that previously, but I did it again and I receive an error that states «Expected: line number or label or statement or end of statement»

    Ensure you have a space then the underscore at the end of the first line.

    Then position the cursor immediately after the underscore at the end of the first line and press Enter.

    If it creates a blank line between the 2 lines then delete that line. (If it does not then the Line Feed between the lines was corrupt. Not a common problem but sometimes this can occur when editing existing code and produces the error you describe.)

    Then position the cursor immediately after the last character in the second line and press Enter.

    Test and see if the problem still exists.


    Regards, OssieMac

    • Marked as answer by

      Monday, December 23, 2013 5:41 PM

I want to use Excel VBA to set up Task Reminders in Outlook, so I found this code from here:
http://www.jpsoftwaretech.com/using-excel-vba-to-set-up-task-reminders-in-outlook/

Dim bWeStartedOutlook As Boolean

Function AddToTasks(strDate As String, strText As String, DaysOut As Integer) As Boolean
=AddToTasks(B2, M2 Time, 120)



' Adds a task reminder to Outlook Tasks a specific number of days before the date specified
' Returns TRUE if successful
' Will not trigger OMG because no protected properties are accessed
' by Jimmy Pena, http://www.jpsoftwaretech.com, 10/30/2008
'
' Usage:
' =AddToTasks("12/31/2008", "Something to remember", 30)
' or:
' =AddToTasks(A1, A2, A3)
' where A1 contains valid date, A2 contains task information, A3 contains number of days before A1 date to trigger task reminder
'
' can also be used in VBA :
'If AddToTasks("12/31/2008", "Christmas shopping", 30) Then
'  MsgBox "ok!"
'End If
 
Dim intDaysBack As Integer
Dim dteDate As Date
Dim olApp As Object ' Outlook.Application
Dim objTask As Object ' Outlook.TaskItem
 
' make sure all fields were filled in
If (Not IsDate(strDate)) Or (strText = "") Or (DaysOut <= 0) Then
  AddToTasks = False
  GoTo ExitProc
End If
 
' We want the task reminder a certain number of days BEFORE the due date
' ex: if DaysOut = 120, then we want the due date to be -120 before the date specified
' we need to pass -120 to the NextBusinessDay function, so to go from 120 to -120,
' we subtract double the number (240) from the number provided (120).
' 120 - (120 * 2); 120 - 240 = -120
 
intDaysBack = DaysOut - (DaysOut * 2)
 
dteDate = NextBusinessDay(CDate(strDate), intDaysBack)
 
On Error Resume Next
  Set olApp = GetOutlookApp
On Error GoTo 0
 
If Not olApp Is Nothing Then
  Set objTask = olApp.CreateItem(3)  ' task item
 
  With objTask
    .StartDate = dteDate
    .Subject = strText & ", due on: " & strDate
    .ReminderSet = True
    .Save
  End With
 
Else
  AddToTasks = False
  GoTo ExitProc
End If
 
' if we got this far, it must have worked
AddToTasks = True
 
ExitProc:
If bWeStartedOutlook Then
  olApp.Quit
End If
Set olApp = Nothing
Set objTask = Nothing
End Function
 
Function GetOutlookApp() As Object
 
On Error Resume Next
  Set GetOutlookApp = GetObject(, "Outlook.Application")
  If Err.Number <> 0 Then
    Set GetOutlookApp = CreateObject("Outlook.Application")
    bWeStartedOutlook = True
  End If
On Error GoTo 0
 
End Function
Sub Test()

My question is, if I have all the data in the spreadsheet, and I initiallize AddToTasks like so:
=AddToTasks(A1, A2, 120)

Why does it come up with that error?

WCDoan


  • #1

I’m trying to create a module that will take a single character code and
return the word it represents. I was using an If statement in 2 reports that
did this fine. I have to create more reports that will use this so I decided
to put the If statement in a function and then use the function in all the
reports. However, I get a compile error when I type in the line to ‘call’ the
function.
This is the If that was working:

If AnimalType = «D» Then
[TypeOf] = «Dog»
ElseIf AnimalType = «C» Then
[TypeOf] = «Cat»
Else
[TypeOf] = «Other»
End
End If
This above works fine. The AnimalType is from the table and the TypeOf is an
unbound field used do print the word on the report.

This is the function:
Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
[TypeAnimal] = «Dog»
ElseIf TypeOfAnimal = «C» Then
[TypeAnimal] = «Cat»
Else
[TypeAnimal] = «Other»
End If
End Function

This is the ‘call’ statement on the Click Event:
TypeOf = TypeAnimal(AnimalType)

*TypeOf is the unbound field on the report that prints the word returned.*
*AnimalType is from the Animal Table*

Error message:
Expected:line number or label or statement or end of statement

Does anyone have any ideas about what’s causing this?

Thanks,
RandyM

Advertisements

John Spencer


  • #2

First, try removing the brackets around the function name.

Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
TypeAnimal= «Dog»
ElseIf TypeOfAnimal = «C» Then
TypeAnimal = «Cat»
Else
TypeAnimal = «Other»
End If

End Function

WCDoan


  • #3

John,
Thanks for answering. I tried removing the brackets, but now the line that
calls the function from an event subroutine turns red when I press enter. The
line is

TypeOf = TypeAnimal(AnimalType).

I don’t understand why this doesn’t work. I had another IF statement I was
using that merged the First and Last names into one name, I turned it into a
function and it works fine. I’ve compared them and I can’t see what I’ve done
differently between the two. This seems like a straight forward process, but
somehow I’m managing to screw it up. Any ideas?

Thanks,
RandyM

John Spencer said:

First, try removing the brackets around the function name.

Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
TypeAnimal= «Dog»
ElseIf TypeOfAnimal = «C» Then
TypeAnimal = «Cat»
Else
TypeAnimal = «Other»
End If

End Function

WCDoan said:

I’m trying to create a module that will take a single character code and
return the word it represents. I was using an If statement in 2 reports
that
did this fine. I have to create more reports that will use this so I
decided
to put the If statement in a function and then use the function in all the
reports. However, I get a compile error when I type in the line to ‘call’
the
function.
This is the If that was working:

If AnimalType = «D» Then
[TypeOf] = «Dog»
ElseIf AnimalType = «C» Then
[TypeOf] = «Cat»
Else
[TypeOf] = «Other»
End
End If
This above works fine. The AnimalType is from the table and the TypeOf is
an
unbound field used do print the word on the report.

This is the function:
Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
[TypeAnimal] = «Dog»
ElseIf TypeOfAnimal = «C» Then
[TypeAnimal] = «Cat»
Else
[TypeAnimal] = «Other»
End If
End Function

This is the ‘call’ statement on the Click Event:
TypeOf = TypeAnimal(AnimalType)

*TypeOf is the unbound field on the report that prints the word returned.*
*AnimalType is from the Animal Table*

Error message:
Expected:line number or label or statement or end of statement

Does anyone have any ideas about what’s causing this?

Thanks,
RandyM

John Spencer


  • #4

I just tested the function in the immediate window and it works for me.

Perhaps TypeOf is the problem.

If the function is in a vba module, then try typing the following in the
immediate window and see if it works

?TypeAnimal(«C»)
Cat

If that works, then you need to look at TypeOf — I have a vague feeling
that TypeOf might be a reserved word. Try changing that to TxtTypeOf =
TypeAnimal(AnimalType)

See if that works.

WCDoan said:

John,
Thanks for answering. I tried removing the brackets, but now the line
that
calls the function from an event subroutine turns red when I press enter.
The
line is

TypeOf = TypeAnimal(AnimalType).

I don’t understand why this doesn’t work. I had another IF statement I was
using that merged the First and Last names into one name, I turned it into
a
function and it works fine. I’ve compared them and I can’t see what I’ve
done
differently between the two. This seems like a straight forward process,
but
somehow I’m managing to screw it up. Any ideas?

Thanks,
RandyM

John Spencer said:

First, try removing the brackets around the function name.

Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
TypeAnimal= «Dog»
ElseIf TypeOfAnimal = «C» Then
TypeAnimal = «Cat»
Else
TypeAnimal = «Other»
End If

End Function

WCDoan said:

I’m trying to create a module that will take a single character code
and
return the word it represents. I was using an If statement in 2 reports
that
did this fine. I have to create more reports that will use this so I
decided
to put the If statement in a function and then use the function in all
the
reports. However, I get a compile error when I type in the line to
‘call’
the
function.
This is the If that was working:

If AnimalType = «D» Then
[TypeOf] = «Dog»
ElseIf AnimalType = «C» Then
[TypeOf] = «Cat»
Else
[TypeOf] = «Other»
End
End If
This above works fine. The AnimalType is from the table and the TypeOf
is
an
unbound field used do print the word on the report.

This is the function:
Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
[TypeAnimal] = «Dog»
ElseIf TypeOfAnimal = «C» Then
[TypeAnimal] = «Cat»
Else
[TypeAnimal] = «Other»
End If
End Function

This is the ‘call’ statement on the Click Event:
TypeOf = TypeAnimal(AnimalType)

*TypeOf is the unbound field on the report that prints the word
returned.*
*AnimalType is from the Animal Table*

Error message:
Expected:line number or label or statement or end of statement

Does anyone have any ideas about what’s causing this?

Thanks,
RandyM

Advertisements

WCDoan


  • #5

John,
Thank you, thank you, thank you. That did it. I changed the name and it
works like a charm. Thanks for taking time to help…I appreciate it. Have a
great weekend.

Thanks again,
RandyM

John Spencer said:

I just tested the function in the immediate window and it works for me.

Perhaps TypeOf is the problem.

If the function is in a vba module, then try typing the following in the
immediate window and see if it works

?TypeAnimal(«C»)
Cat

If that works, then you need to look at TypeOf — I have a vague feeling
that TypeOf might be a reserved word. Try changing that to TxtTypeOf =
TypeAnimal(AnimalType)

See if that works.

WCDoan said:

John,
Thanks for answering. I tried removing the brackets, but now the line
that
calls the function from an event subroutine turns red when I press enter.
The
line is

TypeOf = TypeAnimal(AnimalType).

I don’t understand why this doesn’t work. I had another IF statement I was
using that merged the First and Last names into one name, I turned it into
a
function and it works fine. I’ve compared them and I can’t see what I’ve
done
differently between the two. This seems like a straight forward process,
but
somehow I’m managing to screw it up. Any ideas?

Thanks,
RandyM

John Spencer said:

First, try removing the brackets around the function name.

Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
TypeAnimal= «Dog»
ElseIf TypeOfAnimal = «C» Then
TypeAnimal = «Cat»
Else
TypeAnimal = «Other»
End If

End Function

I’m trying to create a module that will take a single character code
and
return the word it represents. I was using an If statement in 2 reports
that
did this fine. I have to create more reports that will use this so I
decided
to put the If statement in a function and then use the function in all
the
reports. However, I get a compile error when I type in the line to
‘call’
the
function.
This is the If that was working:

If AnimalType = «D» Then
[TypeOf] = «Dog»
ElseIf AnimalType = «C» Then
[TypeOf] = «Cat»
Else
[TypeOf] = «Other»
End
End If
This above works fine. The AnimalType is from the table and the TypeOf
is
an
unbound field used do print the word on the report.

This is the function:
Public Function TypeAnimal(TypeOfAnimal As String) As String

If TypeOfAnimal = «D» Then
[TypeAnimal] = «Dog»
ElseIf TypeOfAnimal = «C» Then
[TypeAnimal] = «Cat»
Else
[TypeAnimal] = «Other»
End If
End Function

This is the ‘call’ statement on the Click Event:
TypeOf = TypeAnimal(AnimalType)

*TypeOf is the unbound field on the report that prints the word
returned.*
*AnimalType is from the Animal Table*

Error message:
Expected:line number or label or statement or end of statement

Does anyone have any ideas about what’s causing this?

Thanks,
RandyM

Berserker_ua

0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

1

Синтаксическая ошибка

26.05.2013, 21:17. Показов 8840. Ответов 17

Метки нет (Все метки)


Вформе есть 2 списка (Список8 и Список12). в Списке8 в соответствии с запросом выводит данные поля таблицы (STAT, KODDIAN, KODDIAZ). При двойном клике по Спискок8 в Списке12 должно открытся данные с табллицы MSXK но в строках & «WHERE STAT = » & Forms!Form5!STAT _
& «AND KODDIAZ = ‘» & Список8.Column(2) & «‘» _
& «ORDER BY NDIA ASC» выводит синтаксическую ошибку. Помогите исправить.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Option Compare Database
Option Explicit
 
Private Sub ПолеСоСписком0_Click()
  Dim strSQL As String
  strSQL = "SELECT * FROM ARKART " & _
   "WHERE STAT = " & ПолеСоСписком0.Column(1)
  Debug.Print strSQL
  Forms!Form5.RecordSource = strSQL
End Sub
Private Sub Form_Load()
 
End Sub
Private Sub Form_Open(Cancel As Integer)
  ПолеСоСписком0.RowSourceType = "Table/Query"
  ПолеСоСписком0.RowSource = "ARKART"
  ПолеСоСписком0.ColumnCount = 2
  ПолеСоСписком0.ColumnWidths = "0"
End Sub
Private Sub Form_Current()
  Список8.Requery
  Список12.RowSource = ""
End Sub
 
Private Sub Список8_DblClick(Cancel As Integer)
Dim strSQL As String
 
  strSQL = "SELECT ARKART.KODDIAZ, MSXK.KODDIA, MSXK.NDIA " _
   & "FROM (MSXK INNER JOIN ARKART ON MSXK.KODDIA=ARKART.KODDIAZ) " _
   & "WHERE STAT = " & Forms!Form5!STAT _
   & "AND KODDIAZ = '" & Список8.Column(2) & "'" _
   & "ORDER BY NDIA ASC"
   
   
 Debug.Print strSQL
 Список12.RowSource = strSQL
End Sub

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

26.05.2013, 21:17

17

81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

26.05.2013, 21:42

2

в строках 31, 32 нужны пробелы, иначе запрос сливается в одну строку

& «WHERE STAT = » & Forms!Form5!STAT _
& » AND KODDIAZ = ‘» & Список8.Column(2) & «‘» _
& » ORDER BY NDIA ASC»



0



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

26.05.2013, 21:54

 [ТС]

3

mcherry, Можно подрбднее? Если вы имеете в виду после » то всё равно не работает.



0



81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

26.05.2013, 21:56

4

в этой же строке ошибка?

когда у меня подобное возникает я в любую свободную ячейку на листе екселя вывожу получившийся запрос (перед его выполнением) и смотрю что там не так, попробуйте и Вы вывести, может где-то еще что-то пропущено….



0



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

26.05.2013, 22:12

 [ТС]

5

я в Access’е пишу, пробовал удалить одну или пару строк всё равно одна и так ошибка
& «WHERE STAT = » & Forms!Form5!STAT _
& » AND KODDIAZ = ‘» & Список8.Column(2) & «‘» _
& » ORDER BY NDIA ASC»
всё время ссылается сюда.

Добавлено через 3 минуты
если написать похожий запрос
SELECT ARKART.KODDIAZ, MSXK.KODDIA, MSXK.NDIA
FROM MSXK INNER JOIN ARKART ON MSXK.KODDIA = ARKART.KODDIAZ
WHERE (((ARKART.[STAT])=[Forms]![Form5]![STAT]))
ORDER BY MSXK.NDIA;
то он работает, но даже если в процедуре удалить & «AND KODDIAZ = ‘» & Список8.Column(2) & «‘» _ , то в процессе работать отказуеться.



0



81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

26.05.2013, 22:18

6

тоже синтаксическую ошибку выдает? попробуйте текст запроса выдать в меседж-боксе…



0



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

26.05.2013, 22:33

 [ТС]

7

Не сильно понимаю как это можно осуществить.



0



81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

26.05.2013, 22:39

8

MsgBox strSQL

и будет видно где ошибка в синтаксисе запроса



0



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

26.05.2013, 22:55

 [ТС]

9

Вы имеете в виду записать:
MsgBox strSQL = «SELECT ARKART.KODDIAZ, MSXK.KODDIA, MSXK.NDIA » _
& «FROM (MSXK INNER JOIN ARKART ON MSXK.KODDIA=ARKART.KODDIAZ) » _
& «WHERE STAT = » & Forms!Form5!STAT _
& «AND KODDIAZ = ‘» & Список8.Column(2) & «‘» _
& «ORDER BY NDIA ASC»
Если да ошибка таже.



0



mcherry

81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

26.05.2013, 23:00

10

нет,

Visual Basic
1
2
3
4
5
6
7
strSQL = "SELECT ARKART.KODDIAZ, MSXK.KODDIA, MSXK.NDIA " _
& "FROM (MSXK INNER JOIN ARKART ON MSXK.KODDIA=ARKART.KODDIAZ) " _
& " WHERE STAT = " & Forms!Form5!STAT _
& " AND KODDIAZ = '" & Список8.Column(2) & "'" _
& " ORDER BY NDIA ASC"
 
MsgBox strSQL

+ не забываем пробелы после » на новой строке с частью запроса



0



Berserker_ua

0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

26.05.2013, 23:29

 [ТС]

11

Измененная строка

Visual Basic
1
2
3
4
5
6
strSQL = " SELECT ARKART.KODDIAZ, MSXK.KODDIA, MSXK.NDIA " _
   & " FROM (MSXK INNER JOIN ARKART ON MSXK.KODDIA=ARKART.KODDIAZ) " _
   & " WHERE STAT = " & Forms!Form5!STAT _
   & " AND KODDIAZ = '" & Список8.Column(2) & "'" _
   & " ORDER BY NDIA ASC"
   MsgBox strSQL

и всё равно таже ошибка
а при изменения строк & » WHERE STAT = » & Forms!Form5!STAT _
& » AND KODDIAZ = ‘» & Список8.Column(2) & «‘» _
& » ORDER BY NDIA ASC»
выдает ошибку Compile error: Expected: line number or label or statement or end of statement

Добавлено через 2 минуты
Сейчас запучтил, выдало False а потом пустое окно.



0



81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

26.05.2013, 23:45

12

Проверьте возвращают ли нужные значения Forms!Form5!STAT и Список8.Column(2), пустое сообщение не должно выводиться, т.к. «MsgBox strSQL» выводит содержимое переменной — в данном случае текст запроса



1



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

27.05.2013, 00:02

 [ТС]

13

Благодарю Вас за помощь, надеюсь исправлю как-то это. Если у Вас будет желание не могли б просмотреть этот процесс(Form5)



0



mcherry

81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

27.05.2013, 00:18

14

так работает:

Visual Basic
1
2
3
4
5
strSQL = " SELECT ARKART.KODDIAZ, MSXK.KODDIA, MSXK.NDIA " _
   & " FROM (MSXK INNER JOIN ARKART ON MSXK.KODDIA=ARKART.KODDIAZ) " _
    & " WHERE STAT = " & Forms!Form5!STAT _
    & " AND KODDIAZ = '" & Список8.Column(2) & " ' " _
    & " ORDER BY NDIA ASC "

в строке был лишний пробел после AND KODDIAZ = ‘

и получалось что запрос выбирает не KODDIAZ=’F051′, а KODDIAZ=’ F051′

и перед формированием строки запроса MsgBox не нужен…



1



81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

27.05.2013, 00:26

15

вот, поправила:



0



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

27.05.2013, 00:36

 [ТС]

16

Спасибо огромное, но теперь как изменить чтобы в одном из столбцов вторго списка выводилось текст с переменной MSXK.NDIA, просто задача была такая чтобы с первого списка выбрать код диагноза и после двойного нажати во втором выводилась информация про диагноз?

Добавлено через 9 минут
ой, извените, сам увидел))) Еще раз спасиобо вам за помощь



0



81 / 24 / 2

Регистрация: 18.01.2013

Сообщений: 74

27.05.2013, 00:36

17

открыть форму в режиме конструктора, открыть свойства списка 12 (через контекстное меню) и поменять свойство «число столбцов» с 2 на 3.
и еще есть свойство «ширина столбцов» — для наведения красоты (задается в сантиметрах через точку с запятой для каждого столбца)



1



0 / 0 / 0

Регистрация: 22.05.2013

Сообщений: 17

27.05.2013, 00:45

 [ТС]

18

да, уведел уже, просто забыл про это)

Добавлено через 8 минут
mcherry, а немогли б вы глянуть в эту тему Ошибка при экспорте и подсказать как решить или показать какой-то другой пример экспорта данных с таблицы?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

27.05.2013, 00:45

Помогаю со студенческими работами здесь

Ошибка TNS-01150: Указан неверный адрес имени прослушивателя NL-00303: синтаксическая ошибка в NV-строке
после команды lsnrctl status выдает такую ошибку:
TNS-01150: Указан неверный адрес имени…

Ошибка разбора: синтаксическая ошибка, неожиданный ‘а’ (T_WHILE) в C:OSPaneldomainsTest.ruindex.php на линии 15
&lt;?php

$connection = mysqli_connect(‘127.0.0.1′,’mysql’,’mysql’,’test_db’);

if ( $connection…

Ошибка анализа: синтаксическая ошибка, неожиданная «ModelBlogArticle» (T_STRING) в /home/u1607/uggitut.ru/www/admin/mode
помогите исправить ошибку, если это реально!

вот выдает ошибку: Parse error: syntax error,…

Ошибка при вызове метода/Синтаксическая ошибка
Здравствуйте, скажите пожалуйста, возможно ли изменить конструкцию запроса, чтобы не выводило такой…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

18

  1. Compile Error: Expected: line number or label or…

    Good afternoon all, I’m running into this error and can’t for the life of me figure out how to fix it.

    Compile Error: Expected: line number or label or statement or end of statement

    This is the code I am using (its in an if statement if that helps).

    Code:

    "Update tblLogTemp set LogOffDate(Sql1) = LOD(sql2), LogOffTime = LOT(sql2)" &_
    "where (SELECT top 1 dbo_Logoffs.Operdate as LOD, dbo_Logoffs.opertime as LOT" &_
    "FROM dbo_Logoffs INNER JOIN tblLogTemp ON dbo_Logoffs.FullName = tblLogTemp.User" &_
    "Where dbo_Logoffs.OperDate >= tblLogTemp.LogOnDate and dbo_LogOffs.OperTime >= tblLogTemp.LogOffTime);"

    Any ideas?


  2. immediately I see 2 things:

    • replace «&_» with «& _»
    • at the end of each line, add a space before you close the statement portion with a double quote:

    that’s the cause of the error


  3. I did both of those things (i tried the & _ as opposed to the &_ previously but forgot to change it back), but the space before the » I didn’t realize mattered.

    But I am getting the same error still.


  4. what’s the entire code? and what line errors out? by default, it should highlight one in yellow. If it doesn’t, go into the options and push the radio button that says «break on all errors».

    looking at the statement itself, I’ve never seen anything like it. what are you doing exactly? It looks like you’re trying to update a function WITH a function??

    And why is there no comparison value on the right side of your first WHERE clause?

    I’m having a heck of a time reading and interpreting this sql. I might not be the best person to help you here…


  5. I don’t use VBA often (in all honesty I haven’t written anything serious in the access VBA in 6 years so my VBA knowledge, at best, can be considered rusty. At worst it can be considered beginner level) so I am kind of grasping at straws with what i’m trying to do..

    Quick breakdown of what I am trying to do.

    I need to pull Logon Dates/TImes from Table1, and Logoff dates/times from Table2. There is no direct corellation between the 2 so basically what i’m doing in order to create a report listing them both is using a temp table to house all 4 dates/times and create a report based on it.

    So Sql1 fills the temp table with user, logon date, logontime. And the Sql i’m attempting to write is (theoretically) going to update that table with the logoff date, and logofftime.

    So in theory

    if recordset.eof = false
    then Update TempTable set Logoffdate = Table2.logoffdate, logofftime = table2.logofftime where temptable.user = table2.user, logoffdate >= date and <= date

    Since there is no direct link between the records basically what I am having to do is select the first matching record (Select Top 1 assuming it exists) where the dates kind of match up.

    The date field houses the date, but the time field is formatted incorrectly and houses the date and time both (unfortunately the date it shows though is the default date which is 1/1/1900. Realistically the date/time should just be formatted into 1 field, but whoever designed it set it up in 2 different fields with the wrong formats so its causing me a terrible terrible headache.)

    Sorry about this wall of text. Maybe I’m just overcomplicating it?

    *edit* the comparison value after the first ‘where’ clause should be covered with the select statement inside the parethesis unless i am mistaken.


  6. I think you are overcomplicating, actually.

    I might have a better suggestion. can you post screenshots of both tables’ structures?

    you said there’s no correlation between the two? WHY are you doing it? preparing data for periodic paychecks for staff? I would assume with something like that, the consolidation of the data would have to be correlated somehow, like one record per punch in, punch out?

    regardless, post those tables and let us have a look. post ss’s of both the originals, as well as what you’re new consolidated one is supposed to look like.


  7. I’m doing it because the owner of the company I work for wants a report to show the hours of the salary employees are logged in as a ‘check’ to see if they’re coming in or not. The report will be unreliable, inaccurate, and the dates will be assumed at best, but he doesn’t care he wants to see it.

    The reason I say there is no correlation is because the user can login multiple times without having logged out once. The record input is based on login and logoff scripts. If neither is run then it won’t record a new record.

    Here is the layout of the tables. Both tables have the same layout.

    ID as Autonumber (PK)
    OperDate as Date/Time
    Opertime as Date/Time
    FullName as Text
    Host as Text
    IP as Text
    Asset as Text
    Oper as Text

    Now there is no direct relation between the 2 tables, but you can ‘assume’ that the host and ip will be the same for login/logoff’s but you will run into cases where the dates don’t match up (for instance on one example there were 24 logins, and 16 logoffs).

    Which is why i’m running the query to pull what I would consider an ‘assumed’ match. To pull the match it’s a simple select query that just goes ‘select top 1 date, time from logoffs where logoff.date >= logondate and user = user). The top 1 is just to it pulls the first possible match as opposed to 4 possible matches and updates itself repeatedly.


  8. well first of all sir, you didn’t post any screenshots, which is what I asked about.

    is that not possible? simply copy the tables, delete all the data and print the screen. that would help, but the explanation works fine I suppose. But what about the 3rd table? I personally still can’t my head around it.

    how about posting the script you’re using to do this with? You said it was in the middle of an »if» statement. post it please.

    If you’re wanting to execute UPDATE statements everytime you go through a loop, I would be more inclined to tell you to open 2 recordsets and write values from one to the other, simply because it probably uses less memory stacking and processor resource. If too much resource is requested from a machine too fast, strange things can come out of it, and sometimes it’s a computer crash. As a matter of fact, I’ve had this happen to me with vba scripts and I’ve gotten back garbage that didn’t make any sense and wasn’t even related to the output I requested via the script.


  9. Hi Rabozza,

    maybe try to start a total different approach: why not make a union query combining the logins and logouts in 1 dataset. Something like:

    Code:

    SELECT tblLogin.Host, tblLogin.IP, tblLogin.FullName, tblLogin.OperDate, tblLogin.OperTime, "Login" as flfType
    FROM tblLogin
    UNION
    SELECT tblLogout.Host, tblLogout.IP, tblLogout.FullName, tblLogout.OperDate, tblLogout.OperTime,  "Logout" as flfType
    FROM tblLogout
    ORDER BY  tblLogin.OperDate, tblLogin.OperTime, tblLogin.Host, tblLogin.IP, tblLogin.FullName;

    The sorting can be different, according to your needs of course. Then you can use this dataset as a base for a report (maybe use a crosstab?)

    succes
    NG



    • #1

    Hi,
    I am trying to pass the column value of cells with values not equal to zero to variables F1, F2, F3 , F4, F5 & F6. The code is as under;

    Dim i, F1, F2, F3, F4, F5, F6 As Integer
    Set TsRng = Range("E3:J3")
    i = 1
    For Each Ts In TsRng
        If Ts.Value <> 0 Then
            "F" & i = Ts.Column
            i = i + 1
        End If
    Next

    I get a compile error message for the line «F» & i = Ts.column. Not sure what I am doing wrong here. Please help.
    Thanks in advance.

    • #2

    Re: Compile Error: Expected: line number or label or statement or end of statement

    Is it really necessary to put the values into the variables
    you can try putiing the values into a variant on a temp basis unntil you get an answer for this which will be easier if you r stuck and want to procede further with your development

    • #3

    Re: Compile Error: Expected: line number or label or statement or end of statement

    Hi ashu1990,

    Thanks for your response.

    Could you please elaborate on how to put the values into a variant? Sorry if I sound ignorant.

    Cheers,

    • #4

    Re: Compile Error: Expected: line number or label or statement or end of statement

    You could use an array:

    Dim i As Integer, F(1 To 6) As Integer
    Set TsRng = Range("E3:J3")
    i = 1
    For Each Ts In TsRng
        If Ts.Value <> 0 Then
            F(i) = Ts.Column
            i = i + 1
        End If
    Next
    • #5

    Re: Compile Error: Expected: line number or label or statement or end of statement

    Hi rory,
    Thanks, that works!!! Much appreciated. :rock:

    Cheers,

    • #6

    I get same error while using the following code: Anyone to assist? Thanks in advance

    Sub CopyFile()
    Dim SourceFile As String
    Dim DestFile As String
    
    
    SourceFile=“C:Usersk.kamranDesktopFile1.xlsx”
    DestFile = “C:Usersk.kamranDesktopNewFile.xlsx”
    
    
    FileCopy SourceFile, DestFile
    
    
    End Sub

    Display More

    • #7

    Your code works fine here once I replace the smart quotes around your file paths with regular quotes.

    • #8

    kamran1015

    Welcome to the Forum

    Please start your own post. Posting in another member’s Thread is known as hijacking and is not allowed here. By all means add a link to a Thread that may be related to your question.

    • #9

    kamran1015

    Welcome to the Forum. Please read the Forum Rules to understand how the Forum works and why I have added Code Tags to your post

    All VBA code posted in the forum must be wrapped in code tags, which you omitted, including single-line code snippets.Be sure to use them in future posts.

    How to use code tags

    Just highlight all of the code and press the <> in the post menu above button to add the code tags.

    Thanks.

    I suggest you read the Forum Rules before posting again.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Line ends with space python как исправить
  • Line 6777 ошибка
  • Line 3328 error subscript used on non accessible variable forza horizon 4
  • Line 25408 error variable must be of type object что делать
  • Line 25226 file c programdata realtekhd taskhost exe error variable must be of type object

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии