将组合框中的值存储在文件名中

时间:2019-06-16 10:06:58

标签: vba ms-access access-vba

我正在尝试将1或2个组合框的值存储在文件名中。

未选择任何内容时,要保存的文件名为OverzichtTotaal

在组合框交易(Me.KeuzeTransactie)中选择某项(买,卖...)时,要保存的文件名应为Overzicht Buy...

在第二个组合框年份(Me.KeuzeDatum)中选择年份时,文件名应为Overzicht 2015

并且在两个组合框中均选中某项时,名称应为Overzicht 2015 Buy...

Private Sub CmdSave_Click()
    If Me.FilePath = "" Or IsNull(Me.FilePath) Then
        MsgBox "Kies een path!"
        Exit Sub
    End If

    If Right(Me.FilePath, 1) <> "\" Then Me.FilePath = Me.FilePath & "\"

    If Dir(FilePath, vbDirectory) = "" Then
        Shell ("cmd /c mkdir """ & FilePath & """")
    End If

    pathName = Me.FilePath

    If Me.KeuzeTransActie = "" Then
        fileName = pathName & " " & Format(Date, "yyyy-mm-dd") & " " & "OverzichtTotaal.pdf"
    End If
    If Not IsNull(Me.KeuzeDatum) Then
        fileName = pathName & " " & Format(Date, "yyyy-mm-dd") & " " & "Overzicht" & "Jaar.pdf"
    End If
    If Not IsNull(Me.KeuzeTransActie) Then
        fileName = pathName & " " & Format(Date, "yyyy-mm-dd") & " " & "Overzicht" & "Transactie.pdf"
    End If
    'fileName = pathName & " " & Format(Date, "yyyy-mm-dd") & " " & "Overzicht.pdf" & "Jaar" & "Transactie"
    DoCmd.OutputTo acOutputReport, "rptOverzicht", acFormatPDF, fileName, , , , acExportQualityPrint
    'DoCmd.Close acReport, "rptOverzicht"

1 个答案:

答案 0 :(得分:2)

每个模块的标头中都应包含Option Explicit。这将需要变量声明并有助于查找拼写错误。在VBE中设置Tools>Options>Editor>check RequireVariableDeclaration,以便默认情况下将包括新模块。

串联的引用组合框。请注意在串联中使用+字符。使用Null的算术运算结果为Null,因此使用+连接带有空格的组合框时,如果combobox为Null,则不会连接任何多余的空间。与&的串联将忽略Null(除非所有输入均为null)并返回字符串部分。这假定组合框不能包含空字符串。

Option Compare Database
Option Explicit
_________________________________________________

Private Sub CmdSave_Click()
    Dim fileName As String, booSave As Boolean

    With Me

        If .FilePath & "" = "" Then
            MsgBox "Kies een path!"

        Else

            If Right(.FilePath, 1) <> "\" Then .FilePath = .FilePath & "\"

            If Dir(.FilePath, vbDirectory) = "" Then MkDir .FilePath

            fileName = .FilePath & Format(Date, "yyyy-mm-dd") & " Overzicht" _
                 & Nz(" " + .KeuzeDatum & " " + .KeuzeTransActie.Column(1), "Totaal") & ".pdf"

            booSave = True
            If Dir(filename) <> "" Then
                If MsgBox("File already exists, do you want to overwrite?", vbYesNo) = vbNo Then booSave = False
            End If
            If booSave Then DoCmd.OutputTo acOutputReport, "rptOverzicht", acFormatPDF, fileName, , , , acExportQualityPrint

        End If

    End With

End Sub