[英]How to get path and file name for import to Excel using VBA
我有一個 demo.xlsm 文件,當我打開工作簿時會自動運行宏,但它需要讀取 .csv 文件以獲取數據和 Lamda_Logo.png 文件。 Lamda_Logo.png 始終具有相同的名稱。 .csv 文件的名稱未知,但它將與我的 demo.xlsm 具有相同的路徑
如何在 VBA 代碼中使用變量來引用我的 csv 文件的路徑和名稱?
我試過了
csvPath = Dir(Thisworkbook.Path & "\*.csv")
但它不起作用。 唯一有效的命令是
ThisWorkbook.Path & "\Lamda_Logo.png"
加載圖片,但我不能對 .csv 文件做同樣的事情,因為我不知道名字..
這是我的代碼:
Private Sub Workbook_Open()
Dim ws As Worksheet
Dim imagePath As String
Dim imgLeft As Double
Dim imgTop As Double
Set ws = ActiveSheet
imagePath = ThisWorkbook.Path & "\Lamda_Logo.png"
imgLeft = ActiveCell.Left
imgTop = ActiveCell.Top
'Width & Height = -1 means keep original size
ws.Shapes.AddPicture _
fileName:=imagePath, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=imgLeft, _
Top:=imgTop, _
Width:=-1, _
Height:=-1
Dim fileName As String, folder As String
folder = ThisWorkbook.Path & "\"
fileName = "#Lamda_Dev_Projects_Risk_Register_191020211650.csv"
ActiveCell.Offset(1, 0).Range("A12").Select
With Worksheets("Sheet1").Range("A13:T13")
.Font.Size = 12
End With
Worksheets("Sheet1").Range("A13:T13").Font.Bold = True
Range("A13:T13").Interior.Color = RGB(147, 175, 186)
With ActiveSheet.QueryTables _
.Add(Connection:="TEXT;" & folder & fileName, Destination:=ActiveCell)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
'check for filter, turn on if none exists
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A13").AutoFilter
End If
End Sub
我試過了
csvPath = Dir(Thisworkbook.Path & "\*.csv")
但它不起作用。 唯一有效的命令是
ThisWorkbook.Path & "\Lamda_Logo.png"
加載圖片,但我不能對 .csv 文件做同樣的事情,因為我不知道名字..
Dir
函數將返回 File Name ,但沒有Path 。 因此,如果您的工作簿是“D:\\Files\\Testing\\Workbook1.xlsx”,而您的 CSV 是“D:\\Files\\Testing\\Data_20211020.csv”,則:
ThisWorkbook.Path
將是“D:\\Files\\Testing”Dir(ThisWorkbook.Path & "\\*.csv")
將是 "Data_20211020.csv"csvPath
結果是“D:\\Files\\Testing\\Data_20211020.csv”因此,完整路徑將是
csvPath = ThisWorkbook.Path & "\" & Dir(ThisWorkbook.Path & "\*.csv")
(請記住, Dir
將返回一個與掩碼/過濾器匹配的偽隨機文件,再次調用Dir()
將返回另一個文件,直到它們全部返回。如果您有多個 CSV 文件,您可能需要一個更具體的過濾器,比如Dir(ThisWorkbook.Path & "\\Data_*_Processed.csv")
什么的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.