Compile error the code in this project

Hello
  • Remove From My Forums
  • Question

  • Hello

    I’v a problem:

    Compile error: The code in this project must be updated for use on 64-bit systems

    after add PtrSafe this problem disapear but shows another: run time error 13

    in this code:

    Do While Cells(L, «CT»).Value <> «»

    when I change «CT» to the number of column, problem doesn’t disapear…

    when I change «CT» to the number of column there is no data everything goes ok but macro no copy data:)

    Function in the column CT looks like this:

    =JEŻELI(WARTOŚĆ(PRAWY(KOMÓRKA(«nome.arquivo»;W[-8]K[-97]);DŁ(KOMÓRKA(«nome.arquivo»;W[-8]K[-97]))-SZUKAJ.TEKST(«]»;KOMÓRKA(«nome.arquivo»;W[-8]K[-97]))))=1;1;1+ADR.POŚR(ADRES(329;NR.KOLUMNY();;;WARTOŚĆ(PRAWY(KOMÓRKA(«nome.arquivo»;W[-8]K[-97]);DŁ(KOMÓRKA(«nome.arquivo»;W[-8]K[-97]))-SZUKAJ.TEKST(«]»;KOMÓRKA(«nome.arquivo»;W[-8]K[-97]))))-1)))

    And now the best.

    File is from Brazil, it is work perfect on German office 2013 Pro Plus,

    it doesn’t work on Poland office 2013

    what to do???

    • Moved by

      Friday, June 10, 2016 6:35 AM
      VBA related issue

    • Edited by
      Cyprian83
      Friday, June 10, 2016 3:10 PM

We have been using MS Access database (Office 2007, 32bit) in Windows 7 for a long time but recently we switched into Office 2016, 64 bit.

Now every form is displaying the following message and it’s really irritating:

this message

Moreover, the Access window is not getting minimized. I’m not an expert in VBA and don’t know what to do. I’m pasting the codes. Please don’t suggest any article or documentation provided by Microsoft. I have tried to understand those a lot and failed.

The code being used is:

Option Compare Database
Private Declare Function SetWindowPos Lib "user32.dll" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long

And:

Private Sub Form_Load()
    Application.RunCommand (acCmdAppRestore)
    SetWindowPos Application.hWndAccessApp, 0, 0, 0, 0, 0, 0
    Application.DoCmd.MoveSize 0, 0
End Sub

Previously (in 32-bit office) the Access window used to be hidden on form load but now in 64-bit it’s wide open. Please help me to hide the MS Access window in 64-bit version.

В приложениях Visual Basic for Application в Microsoft Office 2010 может возникнуть следующая ошибка:

Compile error:
The code in this project must be updated for use on 64-bit systems.
Please review and update Declare statements and then mark them with the PtrSafe attribute.

Проблема известная, описана в базе знаний Microsoft как KB983043. Решается добавлением слова  PtrSafe после слова Declare. Для примера на рисунке было:

Private Declare Function URLDownloadToFile...

стало

Private Declare PtrSafe Function URLDownloadToFile...

Но согласно заметке http://msdn.microsoft.com/en-us/library/gg251723.aspx:

Adding the PtrSafe keyword to a Declare statement only signifies the Declare statement explicitly targets 64-bits, all data types within the statement that need to store 64-bits (including return values and parameters) must still be modified to hold 64-bit quantities using either LongLong for 64-bit integrals or LongPtr for pointers and handles.

потребуется изменение типов: LongLong для хранения любых целых чисел (но в 64-битовом представлении), и LongPtr для указателей и дескрипторов. Теперь заголовок функции выглядит так:

Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _
 ByVal pCaller As LongLong, _
 ByVal szURL As String, _
 ByVal szFileName As String, _
 ByVal dwReserved As LongLong, _
 ByVal lpfnCB As LongLong) As LongLong

Чтобы избежать переделки кода на различных системах, правильно будет написать:

#If Win64 Then
 Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _
  ByVal pCaller As LongLong, _
  ByVal szURL As String, _
  ByVal szFileName As String, _
  ByVal dwReserved As LongLong, _
  ByVal lpfnCB As LongLong) As LongLong
#Else
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _
 ByVal pCaller As Long, _
 ByVal szURL As String, _
 ByVal szFileName As String, _
 ByVal dwReserved As Long, _
 ByVal lpfnCB As Long) As Long
#End If

Рекомендую также прочитать http://msdn.microsoft.com/en-us/library/ee691831.aspx.

Содержание

  1. Compile error when you edit a VBA macro in the 64-bit version of an Office 2010 program
  2. Symptoms
  3. Resolution
  4. More Information
  5. Steps to reproduce the problem
  6. Ошибка компиляции при редактировании макроса VBA в 64-разрядной версии программы Office 2010
  7. Симптомы
  8. Решение
  9. Дополнительная информация
  10. Действия по воспроизведению проблемы
  11. Compile error: The code in this project must be updated for use on 64-bit systems
  12. All replies

Compile error when you edit a VBA macro in the 64-bit version of an Office 2010 program

Symptoms

Consider the following scenario:

You write a Microsoft Visual Basic for Applications (VBA) macro code that uses Declare statements.

Your VBA macro code uses compilation constants. For example, your macro code uses one the following compilation constants:

You use an #Else block in a conditional block. In the #Else block, you use syntax for a Declare statement designed to run in Microsoft Visual Basic for Applications 6.0.

You edit the code in a 64-bit version of a Microsoft Office 2010 program.

You try to change the Declare statement in the #Else block.

In this scenario, you receive the following error message:

This issue only occurs when you edit the VBA macro. This issue does not occur when you run the macro.

Resolution

To resolve this issue, ignore the «Compile error» and run the VBA code in the 64-bit version of the Office 2010 program.

More Information

Steps to reproduce the problem

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:

Start the 64-bit version of Microsoft Excel 2010 that is running on a Windows 64-bit operating system.

By default, a new workbook is opened.

Press ALT+F11 to start the Visual Basic for Applications 7.0 IDE window.

On the Insert menu, click Module.

In the code window that appears, copy and paste the following code:

In each Declare statement, manually change the name of any parameter that is passed from «ms» to «millisecs.»

When you change the second Declare statement, Visual Basic for Applications 7.0 will report an error that indicates that you have to use PtrSafe. However, the report is incorrect because the line is in a section that only runs in Visual Basic for Applications 6.0. VBA 6.0 does not use PtrSafe. Therefore, you can safely ignore the error message.

Источник

Ошибка компиляции при редактировании макроса VBA в 64-разрядной версии программы Office 2010

Симптомы

Рассмотрим следующий сценарий.

Вы пишете код макроса Microsoft Visual Basic для приложений (VBA), который использует операторы Declare.

Код макроса VBA использует константы компиляции. Например, в коде макроса используется одна из следующих констант компиляции:

Блок #Else в условном блоке. В блоке #Else используется синтаксис для инструкции Declare, предназначенной для выполнения в Microsoft Visual Basic для приложений 6.0.

Код редактируем в 64-разрядной версии программы Microsoft Office 2010.

Вы пытаетесь изменить инструкцию Declare в #Else блока.

В этом случае появляется следующее сообщение об ошибке:

Эта проблема возникает только при изменении макроса VBA. Эта проблема не возникает при выполнении макроса.

Решение

Чтобы устранить эту проблему, пропустите сообщение об ошибке «Компиляция» и запустите код VBA в 64-разрядной версии программы Office 2010.

Дополнительная информация

Действия по воспроизведению проблемы

Корпорация Майкрософт предлагает примеры программного кода только для иллюстрации и не предоставляет явных или подразумеваемых гарантий относительно их корректной работы в конкретных случаях и в пользовательских приложениях. Примеры в данной статье рассчитаны на пользователя, имеющего достаточный уровень знаний соответствующего языка программирования, а также необходимых средств разработки и отладки. Специалисты служб технической поддержки Майкрософт могут пояснить назначение тех или иных конструкций кода в конкретном примере, но модификация примеров и их адаптация к задачам разработчика не поддерживается.

Дополнительные сведения о доступных вариантах поддержки и способах связи с корпорацией Майкрософт см. на следующем веб-сайте Майкрософт:

Запустите 64-разрядную версию Microsoft Excel 2010, русская версия, которая работает в 64-разрядной операционной системе Windows.

По умолчанию открывается новая книга.

Нажмите клавиши ALT+F11, чтобы Visual Basic для приложений ide 7.0.

В меню Вставка выберите пункт Модуль.

В отобразимом окне кода скопируйте и вставьте следующий код:

В каждом операторе Declare вручную измените имя любого параметра, передаваемого с «ms» на «millisecs».

При изменении второй инструкции Declare Visual Basic для приложений 7.0 сообщает об ошибке, указывав на то, что необходимо использовать PtrSafe. Однако отчет неправильный, так как строка находится в разделе, который выполняется только в Visual Basic для приложений 6.0. VBA 6.0 не использует PtrSafe. Таким образом, можно спокойно игнорировать сообщение об ошибке.

Источник

Compile error: The code in this project must be updated for use on 64-bit systems

after add PtrSafe this problem disapear but shows another: run time error 13

Do While Cells(L, «CT»).Value <> «»

when I change «CT» to the number of column, problem doesn’t disapear.

when I change «CT» to the number of column there is no data everything goes ok but macro no copy data:)

Function in the column CT looks like this:

And now the best.

File is from Brazil, it is work perfect on German office 2013 Pro Plus,

it doesn’t work on Poland office 2013

  • Moved by Ethan Hua Microsoft contingent staff Friday, June 10, 2016 6:35 AM VBA related issue
  • Edited by Cyprian83 Friday, June 10, 2016 3:10 PM

Since your question is related VBA code, I’m moving it to the dedicated Excel for Developers forum for further assistance.

The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.

Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com

thank you for now,

The main key for me what’s a diferences between Brazil/German office and Poland office.

If I need to install additional app or some languages add ins.

I checked this file in Poland on several PC with different Office from 2010 up to 2016 version and it doesn’t work.

For sure this file works on German 2013 Pro Plus Office with Win 7 Pro 64 bit

According to your description, Running VBA code that was written before the Office 2010 release (VBA version 6 and earlier) on a 64-bit platform can result in errors if the code is not modified to run in 64-bit versions of Office. Errors will result because VBA version 6 and earlier implicitly targets 32-bit platforms and typically contains Declare Statements that call into the Windows API using 32-bit data types for pointers and handles. Because VBA version 6 and earlier does not have a specific data type for pointers or handles, it uses the Long data type, which is a 32-bit 4-byte data type, to reference pointers and handles. Pointers and handles in 64-bit environments are 8-byte 64-bit quantities. These 64-bit quantities cannot be held in 32-bit data types, and when the underlying code contains values in the variable or property fields that do not match, the runtime error 13 message appears. So I suggest that you could provide more information about which line code cause throwing runtime error 13, and sample code, screenshot etc., that will help us resolve your issue.

For more information, click here to refer about 64-Bit Visual Basic for Applications Overview

In addition I suggest you should do is read the «International Issues» chapter from the following link:
Excel 2002 VBA Programmer’s Reference
Written by John Green, Stephen Bullen, Rob Bovey and Robert Rosenberg

Disclaimer: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

thank you a lot for help,

this is my code after I used your advice, I add once again PtrSafe and change Long for LongPtr

Public Declare PtrSafe Function FindWindow Lib «user32» Alias «FindWindowA» (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Public Declare PtrSafe Function GetWindow Lib «user32» (ByVal hwnd As LongPtr, ByVal wCmd As Long) As LongPtr
Public Declare PtrSafe Function GetWindowRect Lib «user32» (ByVal hwnd As LongPtr, lpRect As RECT) As Long
Public Declare PtrSafe Function ReleaseCapture Lib «user32» () As Long
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 CreateRectRgn Lib «gdi32» (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As LongPtr
Public Declare PtrSafe Function SetWindowRgn Lib «user32» (ByVal hwnd As LongPtr, ByVal hRgn As LongPtr, ByVal bRedraw As Long) As Long

Public FensterRegion&, Region&
Public Hauptfensternummer&, Clientfensternummer&
Public dummy As LongPtr
Public xInserir_T As Boolean
Public Type RECT
Left As LongPtr
Top As LongPtr
Right As LongPtr
Bottom As LongPtr
End Type

Public Const GW_CHILD = 5
Public Const WM_NCLBUTTONDOWN = &HA1
Public Const HTCAPTION = 2
Public xConta As LongPtr
Sub SemLEgenda(XoBJ As UserForm)
Dim Abmessung As RECT
Dim Abmessung1 As RECT
Dim Pos1x&, Pos1y&, Pos2x&, Pos2y&
If FensterRegion <> 0 Then Exit Sub
UserForm1.BorderStyle = fmBorderStyleSingle
Call Fensternummer(UserForm1, Abmessung, Abmessung1)
Pos1x = 0
Pos1y = (Abmessung1.Top — Abmessung.Top)
Pos2x = Abmessung.Right — Abmessung.Left
Pos2y = Abmessung.Bottom — Abmessung.Top
Region = CreateRectRgn(Pos1x, Pos1y, Pos2x, Pos2y)
FensterRegion = SetWindowRgn(Hauptfensternummer, Region, True)
End Sub
Private Sub Fensternummer(Form As Object, Abmessung As RECT, Abmessung1 As RECT)
Dim Fenstername$, Suchstring$
Suchstring = «UserForm Sem Legenda»
Fenstername = Form.Caption
Form.Caption = Suchstring
Hauptfensternummer = FindWindow(vbNullString, Suchstring)
Form.Caption = Fenstername
Clientfensternummer = GetWindow(Hauptfensternummer, GW_CHILD)
dummy = GetWindowRect(Hauptfensternummer, Abmessung)
dummy = GetWindowRect(Clientfensternummer, Abmessung1)
End Sub

Sub triangulo()
xInserir_T = True
xConta = 0
Call REMOVE_TRIANGULO
xInserir_T = False
‘Call proteger_plan
End Sub

Sub REMOVE_TRIANGULO()
Unload UserForm1
UserForm1.BT_FIM.Visible = False
Application.OnTime Now + TimeValue(«00:00:02»), «REMOVER_OS_TRIAN»
UserForm1.BT_FIM.Visible = False
UserForm1.Show
‘Call proteger_plan
End Sub
Sub REMOVER_OS_TRIAN()
Dim i As Integer
Dim aux_img
Dim aux_ws
Dim L As Integer
UserForm1.Label1.Caption = «Aguarde Removendo Triângulos. »
VBA.DoEvents
Application.ScreenUpdating = False
Application.StatusBar = «AGUARDE. »
xConta = 0
For Each aux_ws In ActiveWorkbook.Worksheets
Application.StatusBar = «AGUARDE. Removendo atividades planejadas da planilha [» & aux_ws.Name & «]. Triângulo(s): » & xConta
If VBA.IsNumeric(aux_ws.Name) Then
aux_ws.Visible = -1
aux_ws.Select
aux_ws.Unprotect «COMAUWCM»
L = 9
Do While Cells(L, «CT»).Value <> «»
‘Do While Cells(L, «CT»).Value <> «» //EISENMANN
L = L + 8
Loop
For Each aux_img In ActiveSheet.Shapes
aux_img.Select
‘AD9 —> X9
If aux_img.Top >= Range(«X9»).Top And aux_img.Top = Range(«X9»).Left And aux_img.Left «»
For i = 24 To 75
If Cells(L, i).Value = True Then
If Cells(L, «L»).Value <> «» Then ‘
Worksheets(«DECOMPOSIÇĂO GERAL»).Shapes(«img_rosa»).Copy
End If
If Cells(L, «J»).Value <> «» Or Cells(L, «K»).Value <> «» Then
Worksheets(«DECOMPOSIÇĂO GERAL»).Shapes(«img_amarelo»).Copy
End If
Cells(L, i).Select
‘Columns(i).Width
ActiveSheet.Paste
Selection.ShapeRange.Top = Cells(L, i).Top + 26
Selection.ShapeRange.Left = Cells(L, i).Left
Selection.ShapeRange.Width = ActiveCell.Width
Selection.ShapeRange.Height = ActiveCell.Height / 2
xConta = xConta + 1
End If
If Cells(L + 1, i).Value = True Then
If Cells(L + 1, «K»).Value <> «» Then
Worksheets(«DECOMPOSIÇĂO GERAL»).Shapes(«img_rosa»).Copy
End If
If Cells(L + 1, «I»).Value <> «» Or Cells(L + 1, «J»).Value <> «» Then
Worksheets(«DECOMPOSIÇĂO GERAL»).Shapes(«img_amarelo»).Copy
End If
Cells(L + 1, i).Select
ActiveSheet.Paste
Selection.ShapeRange.Top = Cells(L + 1, i).Top + 26
Selection.ShapeRange.Left = Cells(L + 1, i).Left
Selection.ShapeRange.Width = ActiveCell.Width
Selection.ShapeRange.Height = ActiveCell.Height / 2
xConta = xConta + 1
End If
If Cells(L + 2, i).Value = True Then
If Cells(L + 2, «K»).Value <> «» Then
Worksheets(«DECOMPOSIÇĂO GERAL»).Shapes(«img_rosa»).Copy
End If
If Cells(L + 2, «I»).Value <> «» Or Cells(L + 2, «J»).Value <> «» Then
Worksheets(«DECOMPOSIÇĂO GERAL»).Shapes(«img_amarelo»).Copy
End If
Cells(L + 2, i).Select
ActiveSheet.Paste
Selection.ShapeRange.Top = Cells(L + 2, i).Top + 26
Selection.ShapeRange.Left = Cells(L + 2, i).Left
Selection.ShapeRange.Width = ActiveCell.Width
Selection.ShapeRange.Height = ActiveCell.Height / 2
xConta = xConta + 1
End If
Next
Application.StatusBar = «AGUARDE. Inserindo Manutençăo Preventiva na Planilha [» & aux_ws.Name & «]. Triângulos: » & xConta
L = L + 8
Loop
End If
Range(«A1»).Select
‘Call gproteger_plan
Next
Worksheets(«1»).Visible = -1
Worksheets(«1»).Select
‘ Application.ScreenUpdating = True
‘ Application.StatusBar = False

Sub Dividir_A_B()
Dim linha As LongPtr
Dim aux_num As LongPtr
Application.StatusBar = «Dividindo itens. Aguarde. »
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
linha = 11
ActiveSheet.Unprotect «COMAUWCM»
aux_num = 0
Do While Cells(linha, 1) <> «»
If Cells(linha, 6).Value > 1 And (Cells(linha, 7).Value = «A» Or Cells(linha, 7).Value = «B») Then
aux_num = aux_num + 1
‘Rows(linha).Copy
‘Rows(linha).Insert Shift:=xlDown
Rows(linha).Select
Selection.Copy
Selection.Insert Shift:=xlDown
Cells(linha, 6).Value = 1
Cells(linha, 5).Value = Cells(linha, 5).Value & » (» & aux_num & «)»
Cells(linha + 1, 6).Value = Cells(linha + 1, 6).Value — 1
If Cells(linha + 1, 6).Value = 1 Then
aux_num = aux_num + 1
Cells(linha + 1, 5).Value = Cells(linha + 1, 5).Value & » (» & aux_num & «)»
End If
Application.CutCopyMode = False
Application.StatusBar = «Dividindo itens. Aguarde. | » & Cells(linha, 2) & » | » & Cells(linha, 3) & » | » & Cells(linha, 4) & » | » & Cells(linha, 5) & » (» & Cells(linha + 1, 6) & «)»
Else
aux_num = 0
End If
linha = linha + 1
Loop
Application.Calculation = xlCalculationAutomatic
ActiveSheet.Protect Password:=»COMAUWCM», DrawingObjects:=True, Contents:=True, Scenarios:= _
False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowSorting:=True, AllowFiltering:=True
Application.ScreenUpdating = True
Application.StatusBar = False
Application.Calculate

End Sub
Sub Lista_op_ml()
If Not VALIDA_OBRIG Then Exit Sub
UF_OP.ListBox1.Clear
Unload UF_OP
UF_OP.ListBox1.Clear
Dim xI As LongPtr
For xI = 1 To Worksheets.Count
If VBA.IsNumeric(Worksheets(xI).Name) Then
UF_OP.ListBox1.AddItem Worksheets(xI).Name
UF_OP.ListBox1.List(UF_OP.ListBox1.ListCount — 1, 1) = «Página: » & Worksheets(xI).Name
End If
Next
UF_OP.Show

End Sub
Sub INICIO()
Application.ScreenUpdating = False
Call exibir_planilha(«PRINCIPAL»)
Application.ScreenUpdating = True
End Sub
Sub DECOMP_GERAL()
If Not VALIDA_OBRIG Then Exit Sub
Call exibir_planilha(«DECOMPOSIÇĂO GERAL»)
‘Call exibir_planilha(«GERAL»)
End Sub
Sub ARV_DECOMP()
Application.ScreenUpdating = False
‘Call exibir_planilha(«ÁRVORE»)
Call exibir_planilha(«ÁRVORE DE DECOMPOSIÇĂO»)
Application.ScreenUpdating = True
End Sub

Sub exibir_planilha(xNome As String)
Worksheets(xNome).Visible = -1
‘ If Worksheets(xNome).Name <> ActiveSheet.Name Then
‘ ActiveSheet.Visible = 2
‘ End If
Worksheets(xNome).Select
End Sub

Function VALIDA_OBRIG() As Boolean
VALIDA_OBRIG = False
Dim xWs As Worksheet
Set xWs = Worksheets(«PRINCIPAL»)
With xWs.Range(«xFabricante»)
If .Value = «» Or VBA.Len(.Value) = 0 Then
VBA.MsgBox «Atençăo, campo FABRICANTE preenchimento obrigatório!», vbCritical, «WCM»
xWs.Visible = -1
xWs.Select
.Select
Exit Function
End If
End With
With xWs.Range(«xFornecedor»)
If .Value = «» Or VBA.Len(.Value) = 0 Then
VBA.MsgBox «Atençăo, campo FORNECEDOR preenchimento obrigatório!», vbCritical, «WCM»
xWs.Visible = -1
xWs.Select
.Select
Exit Function
End If
End With
With xWs.Range(«xUnidOp»)
If .Value = «» Or VBA.Len(.Value) = 0 Then
VBA.MsgBox «Atençăo, campo UNIDADE OPERATIVA preenchimento obrigatório!», vbCritical, «WCM»
xWs.Visible = -1
xWs.Select
.Select
Exit Function
End If
End With
With xWs.Range(«xLinha»)
If .Value = «» Or VBA.Len(.Value) = 0 Then
VBA.MsgBox «Atençăo, campo LINHA preenchimento obrigatório!», vbCritical, «WCM»
xWs.Visible = -1
xWs.Select
.Select
Exit Function
End If
End With
With xWs.Range(«xOperac»)
If .Value = «» Or VBA.Len(.Value) = 0 Then
VBA.MsgBox «Atençăo, campo OPERAÇĂO preenchimento obrigatório!», vbCritical, «WCM»
xWs.Visible = -1
xWs.Select
.Select
Exit Function
End If
End With
With xWs.Range(«xEquipamento»)
If .Value = «» Or VBA.Len(.Value) = 0 Then
VBA.MsgBox «Atençăo, campo EQUIPAMENTO preenchimento obrigatório!», vbCritical, «WCM»
xWs.Visible = -1
xWs.Select
.Select
Exit Function
End If
End With
VALIDA_OBRIG = True
End Function
Sub fechar_sobre()
If UF_Sobre.Visible Then
UF_Sobre.Hide
End If
End Sub

Sub Macro1()

‘ Macro1 Macro
‘ Macro gravada em 21/6/2013 por CMB1168


Columns(«C:C»).EntireColumn.AutoFit
End Sub
Sub Macro2()

‘ Macro2 Macro
‘ Macro gravada em 21/6/2013 por CMB1168


ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:= _
False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowSorting:=True, AllowFiltering:=True
Range(«J15»).Select
End Sub

Option Explicit
Const GWL_STYLE = (-16)
Const WS_CAPTION = &HC00000
Const SWP_FRAMECHANGED = &H20
Public Declare PtrSafe Function FindWindowA Lib «user32» _
(ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Public Declare PtrSafe Function GetWindowLong Lib «user32» Alias _
«GetWindowLongA» (ByVal hwnd As LongPtr, ByVal nIndex As Long) As LongPtr
Public Declare PtrSafe Function SetWindowLong Lib «user32» Alias _
«SetWindowLongA» (ByVal hwnd As LongPtr, ByVal nIndex As LongPtr, _
ByVal dwNewLong As LongPtr) As LongPtr
Public Declare PtrSafe Function SetWindowPos Lib «user32» _
(ByVal hwnd As LongPtr, ByVal hWndInsertAfter As LongPtr, ByVal X As LongPtr, _
ByVal Y As LongPtr, ByVal cx As LongPtr, ByVal cy As LongPtr, _
ByVal wFlags As LongPtr) As LongPtr

Источник

In Excel 2016 I am trying to use the «move and click mouse» macro listed in the below link that simulates mouse click actions in Excel via VBA.
Link: https://excelhelphq.com/how-to-move-and-click-the-mouse-in-vba/

However, after pasting this code in to VBA the first two lines of code are highlighted in red font with an error window popping up with the following message:
Error Window:

Microsoft Vidual Basic Applications

Compile error:

The code in this project must be updated to use on 64-bit systems. Please review and update Declare statements and then mark them with the PtrSafe attribute.

Code lines highlighted in red:

Code:

Public Declare Function SetCursorPos Lib "user32.dll" (ByVal x As Long, ByVal y As Long) As Long
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)

For reference, the complete macro code is listed below:

Code:

Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10

Private Sub SingleClick()
  SetCursorPos 100, 100 'x and y position
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Private Sub DoubleClick()
  'Double click as a quick series of two clicks
  SetCursorPos 100, 100 'x and y position
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Private Sub RightClick()
  'Right click
  SetCursorPos 200, 200 'x and y position
  mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
  mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
End Sub

For reference, I am running Excel 2016 on Windows 10 (64-bit).

How would I correct the above code, so that it works?

Добрый день, уважаемые специалисты.
Помогите справиться с внезапной проблемой.

На одном компьютере — макрос работает нормально.
Но на другом компьютере выдается ошибка :  «Compile error: The code in this project must be updated for use on 64-bit systems. Please review and update Declsre…»

При ошибке выделяется вот этот фрагмент:

Код
Declare Function GetActiveWindow32 Lib "user32" Alias _
                                   "GetActiveWindow" () As Integer

Declare Function SendMessage32 Lib "user32" Alias _
                               "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
                                               ByVal wParam As Long, ByVal lParam As Long) As Long

Declare Function ExtractIcon32 Lib "SHELL32.DLL" Alias _
                               "ExtractIconA" (ByVal hInst As Long, _
                                               ByVal lpszExeFileName As String, _
                                               ByVal nIconIndex As Long) As Long

Как устранить эту ошибку ?

pavliks, Привет, помоги с вопросом, не разобрался как вставить код, чтобы все новые книги созданные на 32 бит офисе запускались на 64 офисе. По тел можешь подсказать?

Код

в автоопен
Visual BasicВыделить код
1
2
3
4
5
6
7
8
9
10
#If VBA7 Then ‘ Office 2010-2013
Private Declare PtrSafe Function GetComputerNameA Lib «kernel32» (ByVal lpBuffer As String, nSize As LongPtr) As LongPtr
#Else ‘ Office 2003-2007
Private Declare Function GetComputerNameA Lib «kernel32» (ByVal lpBuffer As String, nSize As Long) As Long
#End If
#If VBA7 Then ‘ Office 2010-2013
Private Declare PtrSafe Function WNetGetUserA Lib «mpr.dll» (ByVal lpName As String, ByVal lpUserName As String, lpnLength As LongPtr) As LongPtr
#Else ‘ Office 2003-2007
Private Declare Function WNetGetUserA Lib «mpr.dll» (ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As Long
#End If

Добавлено через 49 секунд
mrf,

Добавлено через 1 минуту
Казанский,
Привет, помоги с вопросом, не разобрался как вставить код, чтобы все новые книги созданные на 32 бит офисе запускались на 64 офисе. По тел можешь подсказать?

Код

в автоопен
Visual BasicВыделить код
1
2
3
4
5
6
7
8
9
10
#If VBA7 Then ‘ Office 2010-2013
Private Declare PtrSafe Function GetComputerNameA Lib «kernel32» (ByVal lpBuffer As String, nSize As LongPtr) As LongPtr
#Else ‘ Office 2003-2007
Private Declare Function GetComputerNameA Lib «kernel32» (ByVal lpBuffer As String, nSize As Long) As Long
#End If
#If VBA7 Then ‘ Office 2010-2013
Private Declare PtrSafe Function WNetGetUserA Lib «mpr.dll» (ByVal lpName As String, ByVal lpUserName As String, lpnLength As LongPtr) As LongPtr
#Else ‘ Office 2003-2007
Private Declare Function WNetGetUserA Lib «mpr.dll» (ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As Long
#End If

  • #1

Доброго времени суток, есть макрос написанный на visual basic в таблице эксель.
На одном из компьютеров макрос отказывается работать выдавая ошибку:

Код:

Compile error:
The code in this project must be updated for use on 64-bit systems.
Please rewiew and update Declare statements and then mark them with the PtrSafe attribute.

Я не очень в этом разбираюсь но подозреваю что дело в разрядности ms office или ms windows.
Подскажите как быть и что делать? Может какую то dll надо подрубить?

Surf_rider


  • #2

Так в итоге то где работает и где не работает?

Surf_rider


  • #4

Установлен наверняка 64 разрядный офис. Какая винда? Давайте конкретнее как то..
Товарищи там же написано — добавьте атрибут PtrSafe
Ну и код vb скрипта было бы не плохо…

UEF

UEF

Модератор

Команда форума


  • #6

Попробуйте в таком формате, вставьте PtrSafe как вам посоветовали выше..

Код:

Private Declare PtrSafe Function CoCreateGuid Lib "OLE64.DLL" _

Понравилась статья? Поделить с друзьями:
  • Compile error object required vba
  • Compile error next without for
  • Compile error method or data member not found vba
  • Compile error macro excel
  • Compile error invalid use of property