Ошибка 3075 access

mserg1972

1 / 1 / 2

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

Сообщений: 239

1

30.01.2014, 09:19. Показов 6394. Ответов 13

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


Студворк — интернет-сервис помощи студентам

Ошибка в передаче данных в запрос? или в синтаксисе?

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Private Sub кнопОценитьМагазины_Click()
  Dim sq As String
  Dim cfo As String
  cfo = "М12 Новосибирск Мега (ср)"
  sq = "SELECT Count(*) As kolinv,  -Sum(r = 'САМ') As kolsam" & _
       " FROM (SELECT TOP 3 [Оценка розница] As b, [Присутствие ревизора] As r " & _
       " FROM тблИнвентаризацииОценки" & _
       " WHERE ЦФО = cfo" & _
       " AND Order By ID Desc)"
    With CurrentDb.OpenRecordset(sq)
         MsgBox (!kolinv)
         MsgBox (!kolsam)
    End With
End Sub

Миниатюры

Ошибка 3075 в запросе, пишет отсутствует оператор
 



0



Эксперт MS Access

17320 / 7146 / 1614

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

Сообщений: 13,488

30.01.2014, 09:26

2

Цитата
Сообщение от mserg1972
Посмотреть сообщение

AND здесь зачем, наверное при копировании осталось …?



1



mobile

Эксперт MS Access

26792 / 14471 / 3192

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

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

30.01.2014, 10:14

3

Лучший ответ Сообщение было отмечено mserg1972 как решение

Решение

Плюс к сказанному ltv_1953, обращение к переменной cfo надо выносить из под кавычек

Visual Basic
1
2
" WHERE ЦФО = '" & cfo & "'" & _
" Order By ID Desc)"



1



1 / 1 / 2

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

Сообщений: 239

30.01.2014, 10:43

 [ТС]

4

Если я правильно понял, то при обращении к переменной правильно писать ‘» & cfo & «‘
Спасибо.
AND просмотрел, остался от более сложного запроса.



0



Эксперт MS Access

26792 / 14471 / 3192

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

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

30.01.2014, 11:23

5

Лучший ответ Сообщение было отмечено mserg1972 как решение

Решение

Цитата
Сообщение от mserg1972
Посмотреть сообщение

Если я правильно понял, то при обращении к переменной правильно писать ‘» & cfo & «‘

Запрос не понимает переменных и ему надо предложить значение переменной. А не ее идентификатор.

Апострофы нужны, если переменная текстового типа. Если числовая, то не нужны. Если датная, то в американском формате даты Format(cfo, «\#mm\/dd\/yyyy\#»)



1



mserg1972

1 / 1 / 2

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

Сообщений: 239

31.01.2014, 09:05

 [ТС]

6

Visual Basic
1
Format(cfo, "\#mm\/dd\/yyyy\#")

в чем разница с другим вариантом, он тоже работает

Visual Basic
1
#Format(cfo, "mm\/dd\/yyyy")#



0



mobile

Эксперт MS Access

26792 / 14471 / 3192

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

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

31.01.2014, 10:04

7

Цитата
Сообщение от mserg1972
Посмотреть сообщение

в чем разница с другим вариантом, он тоже работает Код Visual Basic1

Visual Basic
1
#Format(cfo, "mm\/dd\/yyyy")#

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

Visual Basic
1
" WHERE [ПолеДаты] = #" & датнаяпеременная & "#"

Такая запись равнозначна той, которую я привел выше. Символы «#» соединяются с выражением формата с помощью символов конкатенации «&». Но мне лично кажется удобным не разбивать единое выражение на блоки, а записывать их слитно.



1



0 / 0 / 0

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

Сообщений: 16

24.10.2015, 21:14

8

Здравствуйте! У меня вот тоже синтаксическая ошибка:

s = «Select студенты.[фамилия],avg(экзамен.оценка) as среднее, count(экзамен.[код дисциплины])»
s = s & » From студенты, экзамен, дисциплины»
s = s & » Where студенты.[номерзачкнижки] = экзамен.[номерзачкнижки] and экзамен.[код дисциплины] = дисциплины.[код дисциплины]»
s = s & » Group by студенты.[фамилия]»
s = s & » Having count(экзамен.[код дисциплины])=(Select count(дисциплины.[код дисциплины]) From дисциплины and avg(экзамен.оценка)>=4 From экзамен)»

НУЖНО: отобрать всех студентов, сдавших экзамены по всем дисциплинам не менее 4. Что не так?



0



8798 / 5687 / 578

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

Сообщений: 19,173

24.10.2015, 21:22

9

Цитата
Сообщение от ltv_1953
Посмотреть сообщение

AND здесь зачем,

Цитата
Сообщение от mobile
Посмотреть сообщение

А не ее идентификатор.

А Вы ваще точно на Русском языке помогаете ТСу, я вот лично и половины из сказанного не понял.



0



shanemac51

Модератор

Эксперт MS Access

11489 / 4732 / 764

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

Сообщений: 13,746

Записей в блоге: 4

25.10.2015, 08:43

10

Visual Basic
1
From дисциплины and avg(экзамен.оценка)>=4 From экзамен

явно пропущено WHERE и первая часть условия и зачем то второй FROM



0



шапоклякистка 8-го дня

3676 / 2236 / 391

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

Сообщений: 4,647

Записей в блоге: 1

26.10.2015, 08:17

11

Цитата
Сообщение от shanemac51
Посмотреть сообщение

зачем то второй FROM

Там подзапрос



0



Эксперт MS Access

7359 / 4497 / 292

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

Сообщений: 13,719

26.10.2015, 09:18

12

Цитата
Сообщение от Chrono_
Посмотреть сообщение

НУЖНО:

Сначала сделать в конструкторе с нормальными связями, потом sql-представление скопировать в VBA. Представленный ужас с декартовым умножением трёх таблиц даже обсуждать не хочу.



0



шапоклякистка 8-го дня

3676 / 2236 / 391

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

Сообщений: 4,647

Записей в блоге: 1

26.10.2015, 12:43

13

Где там три таблицы? Я вижу только одну, тблИнвентаризацииОценки.

P.S. Хотя в приведенном коде мне кажется странным буквально все, начиная с идеи открывать необновляемый рекордсет, содержащий единственную запись.

Добавлено через 1 минуту
Я бы подзапрос сохранила как объект базы данных, а потом нужные количества и суммы доставала из него функуциями DCount и DSum.



0



Эксперт MS Access

26792 / 14471 / 3192

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

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

26.10.2015, 12:47

14

Цитата
Сообщение от texnik-san
Посмотреть сообщение

Где там три таблицы? Я вижу только одну, тблИнвентаризацииОценки.

Обсуждается пост Ошибка 3075 в запросе, пишет отсутствует оператор И там действительно три

Цитата
Сообщение от Chrono_
Посмотреть сообщение

s = s & » From студенты, экзамен, дисциплины»

Добавлено через 2 минуты
Эта задача уже решена в другом топике Chrono_ — Ошибка 3075



1



  • Remove From My Forums
  • Question

  • the program works fine on my machine, but at my users, it pops up an error message, «3075 The following error occurred: Function is not available in expression in query expression …»
    I never have this problem before. I check reference and there is no MISSING on the list of ref. Do you know why it happens? Please help me to fix this one. Thank you very much.

Answers

  • I am going to check users machine. Since the accde files on user machines don’t have the modules and reference options (to prevent they mess them up), I think I am going to create a blank db on a user and go from there unless you have a better idea.

    Ah, you’re distributing an ACCDE.  Then Access can’t patch the references on the fly, so you need to ensure that you create the ACCDE with the same libraries, in the same locations, as the users’ PCs.

    Are you referencing any non-default libraries?  That’s an obvious source for discrepancies.

    If you take you ACCDB, rather than the ACCDE, over to a user’s PC, does it show any broken references?  Note that Access will automatically fix up some of them, so that may not help a lot.

    It’s possible to write code to simply list all the references, by looping through the application’s References collection; e.g.:

    Sub ListReferencesToFile()
    
        Dim iFileNo As Integer
        
        iFileNo = FreeFile()
        Open "References.txt" For Output As #iFileNo
    
        On Error Resume Next
        
        Dim ref As Reference
        For Each ref In Application.References
            Err.Clear
            Print #iFileNo, ref.Name, ref.FullPath, ref.GUID, ref.Kind, ref.BuiltIn, ref.IsBroken, ref.Major, ref.Minor
            If Err.Number <> 0 Then
                Print #iFileNo, "Error raised on reference ";
                Print #iFileNo, ref.Name;
                Print #iFileNo,
            End If
        Next ref
        
        Close iFileNo
        
    End Sub
    

    You could put such code temporarily into the database, create an ACCDE that calls the code, and compare list that results from running it on your system with the one you get from running it on the user’s system.


    Dirk Goldgar, MS Access MVP
    Access tips: www.datagnostics.com/tips.html

    • Marked as answer by

      Tuesday, October 23, 2012 1:44 PM

Runtime error 3975 is Invalid operator, according to a quick Google search on access vba runtime error 3075 (which you could have made yourself).

The problem is that you only assign a value of "" to stCriteria. If the first if statement executes, stCriteria is then assigned the value of stCriteria AND stCriteria1, which is invalid.

The same thing happens if the second if statement is executed. (In fact, if both are actually run, stCriteria now contains AND stCriteria1 AND stCriteria2, which is even worse.)

The solution is to modify your code to only add the AND if it’s needed:

stLinkCriteria = ""
stDocName = "frmDisplayInfo"

If (Me!txtMainName <> "") Then
    stLinkCriteria = "[Main Applicant Name] Like ' " & Me![txtMainName] & "'"
End If

If (Me!txtIDNo <> "") Then
    If stLinkCriteria <> "" then
        stLinkCriteria = stLinkCriteria & " AND "
    End If
    stLinkCriteria2 = "[ID No] Like ' " & Me![txtIDNo] & "'"
    stLinkCriteria = stLinkCriteria & " And " & stLinkCriteria2
End If

For future reference, the way to solve these kind of problems is to actually examine the value of the variable (in this case stCriteria) just before the line causing the error (here, it’s the DoCmd.OpenForm line) executes. You do so by setting a breakpoint on the line where the error happens, running your app until the breakpoint is hit, and then examining the value of the variable. This shows you exactly what the variable contains, which can reveal the problem.

Symptoms

«Runtime Error 3075: Syntax Error (missing operator) in query expression ID () and Link LIKE ‘SET'»This error occurs when exporting a row format to a .tdb file.

Cause

Exporting a row format that includes Account Sets, and one or more of the accounts sets is invalid or empty.

Resolution

Delete the problematic Account Set from the row format, or correct the Account Set problem by verifying that it exists and that valid accounts are listed. For additional information on working with Accounts Sets, please see How to Create Account Sets in FRx.

References

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

  • Remove From My Forums
  • Question

  • A simple query, the WHERE clause is giving a 3075 error on even a simple entry.

    Field: TestName

    Table: Parameters

    Total: Where

    Criteria: 10

    Try to save or view the SQL and it returns: Syntax error in query expression ‘(((Parameters.[TestName])=»10″))’.

    Click Help, it says: <Message> in query expression <expression>. (Error 3075)

    The expression you typed is not valid for the reason indicated in the message. Make sure you have typed field names and punctuation correctly, and then try the operation again.

    The error is spreading to another query that I was looking at for comparison.  The other query pulls a parameter from a form.  The query runs fine when another query calls it, but I can’t open in it design view anymore.  Do I have a virus
    or something causing this problem?

Answers

  • The problem was that I had a table named Parameters and a form named Parameters and it was confusing the query.  I changed the names to tblparameters and frmparameters and all the places these objects were called and no more error.

    Why that didn’t matter before and why my table and form that are both named Samples didn’t produce the same error?  I don’t know.  But from now on I will use those prefixes and no spaces in names, etc, to avoid any sensitivities that Access has
    about it.

    Thank you Jaynet Zhang for your suggestions.

    • Marked as answer by

      Wednesday, June 6, 2012 2:46 PM

Понравилась статья? Поделить с друзьями:
  • Ошибка 3087 access
  • Ошибка 304 рено сандеро
  • Ошибка 308 что значит
  • Ошибка 304 отис
  • Ошибка 308 на котле аристон clas evo