如何在VBA中获取临时文件名

分类:代码, 博客 标签:

使用VBA开发应用程序时,可能会需要在磁盘上创建一个临时目录或文件,本文提供一个在VBA中创建临时文件的函数Get_Temp_File_Name。它使用到了Windows API函数中的GetTempFileName函数,同时支持对返回的文件名的前缀及扩展名设置。

Option Explicit
'================================
' VBA中获取临时文件名
'
' http://www.cnhup.com
'================================
Private Declare Function GetTempPath Lib "kernel32" _
  Alias "GetTempPathA" _
  (ByVal nBufferLength As Long, _
  ByVal lpBuffer As String) As Long
Private Declare Function GetTempFileName Lib "kernel32" _
  Alias "GetTempFileNameA" _
  (ByVal lpszPath As String, _
  ByVal lpPrefixString As String, _
  ByVal wUnique As Long, _
  ByVal lpTempFileName As String) As Long

Public Function Get_Temp_File_Name( _
  Optional sPrefix As String = "VBA", _
  Optional sExtensao As String = "") As String
  Dim sTmpPath As String * 512
  Dim sTmpName As String * 576
  Dim nRet As Long
  Dim F As String
  nRet = GetTempPath(512, sTmpPath)
  If (nRet > 0 And nRet < 512) Then
    nRet = GetTempFileName(sTmpPath, sPrefix, 0, sTmpName)
    If nRet <> 0 Then F = Left$(sTmpName, InStr(sTmpName, vbNullChar) - 1)
    If sExtensao > "" Then
      Kill F
      If Right(F, 4) = ".tmp" Then F = Left(F, Len(F) - 4)
      F = F & sExtensao
    End If
    Get_Temp_File_Name = F
  End If
End Function

Sub Test_Get_Temp_File_Name()
    Debug.Print Get_Temp_File_Name
End Sub


分类:代码, 博客 标签:

发表评论

You must be logged in to post a comment.