【问题标题】:Excel VBA incompatibility kernel32 callsExcel VBA 不兼容 kernel32 调用
【发布时间】:2012-03-11 04:46:07
【问题描述】:

我在 VBA 中有以下代码,在 Excel 2003 中运行良好。 将模板迁移到 Excel 2007 不起作用。

Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As Any, ByVal lpFileName As String) As Long

Private Sub Workbook_Open()
Exit Sub


Dim WorksheetName As String
Dim WorksheetCell As String
Dim Section As String
Dim kKey As String
Dim lLine As Long
Dim InvoiceNumber As Long
Dim InvoiceNumberCell As Object
Dim TemplateName As String
Dim IniFileName As String
Dim Dummy As Variant

    TemplateName = "MyInvoicesTemplate.xlt"
    WorksheetName = "Invoice"
    WorksheetCell = "H2"
    Section = "Invoice"
    kKey = "Number"
    IniFileName = "C:\Windows\Temp\InvoiceNumber.txt"

    Set InvoiceNumberCell = Worksheets(WorksheetName).Range(WorksheetCell)
    If UCase(ActiveWorkbook.Name) = UCase(TemplateName) Then GoTo Finito
    Dummy = GetString(Section, kKey, IniFileName)
    If Left(Dummy, 1) = Chr$(0) Then
        InvoiceNumber = 1
    Else
        InvoiceNumber = CLng(Dummy) + 1
    End If
    WritePrivateProfileString Section, kKey, CStr(InvoiceNumber), IniFileName
    InvoiceNumberCell.Value = InvoiceNumber
    With ActiveWorkbook.VBProject.VBComponents(ActiveWorkbook.CodeName).CodeModule
        lLine = .ProcBodyLine("Workbook_Open", vbext_pk_Proc)
        .InsertLines lLine + 1, "Exit Sub"
    End With
Finito:
Set InvoiceNumberCell = Nothing
End Sub

Function GetString(Section As String, Key As String, File As String) As String
    Dim KeyValue As String
    Dim Characters As Long
    KeyValue = String(255, 0)
    Characters = GetPrivateProfileString(Section, Key, "", KeyValue, 255, File)
    If Characters > 1 Then
        KeyValue = Left(KeyValue, Characters)
    End If
    GetString = KeyValue
End Function

任何想法为什么会发生这种情况? 我尝试以不同的格式保存模板,但没有运气!

谢谢。 MK

【问题讨论】:

  • Dick Kusleika 链接肯定会帮助你。另外,为什么在 Private Sub Workbook_Open() 的开头有“Exit Sub”

标签: vba excel excel-2007 excel-2003


【解决方案1】:

如果您使用的是 64 位 Office,则 API 已更改。见

http://www.jkp-ads.com/articles/apideclarations.asp

【讨论】:

  • +1 虽然用户没有提到 64 位,但错误消息把它全部泄露了 :)
【解决方案2】:

API 已更改。

如果是VBA7,声明ptrSafeLongPtr

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2015-01-26
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多