【发布时间】:2016-04-04 04:43:13
【问题描述】:
我编写了一个宏作为插件,以便在我打开的任何工作簿中都可以使用它。此宏将自动将 Excel 文件另存为 CSV 文件。当我打开一个新工作簿 (newwb.xlsx) 并应用此插件时,我希望我的代码能够自动找到我保存此 newwb.xlsx 的路径并将其保存在同一位置。
我在网上发现Application.ActiveWorkbook.Path可以用来定位路径本身,Application.ActiveWorkbook.FullName可以用来定位带有工作簿名称的路径。但是,它只返回 AddIn 文件的路径名,而不是 newwb.xlsx 的路径名。
如何获取新工作簿文件的文件路径?
这是我的代码:
'Declare the data type of the variables
Dim wks As Worksheet
Dim lastCol As Integer
Dim lastRow As Long
Dim iCol As Integer
Dim iRow As Long
Dim sFilename As String
Dim cellValue As String
Dim MyTextFile
'Set wks to the current active worksheet
Set wks = ActiveWorkbook.ActiveSheet
'Set the location of the csv file to a variable
sFilename = Application.ActiveWorkbook.FullName & "\newwb.csv"
'Within the current active worksheet, identify the last interested row and column of data
'Any values such as 'a', '1' or '%' are considered as values. Spaces (Spacebars) are not considered as values.
With wks
With .Cells(1, 1).CurrentRegion
lastCol = .Columns.Count
lastRow = .Rows.Count
End With
'Delete extra rows with blank spaces
For iRow = 1 To lastRow
For iCol = 1 To lastCol
cellValue = wks.Cells(iRow, iCol)
Next iCol
If Trim(cellValue) = "" Then
wks.Cells(iRow, iCol).EntireRow.Clear
wks.Cells(iRow, iCol).EntireColumn.Clear
End If
Next iRow
'Delete extra rows and columns with formats
.Cells(lastRow + 1, 1).Resize(Rows.Count - lastRow, 1).EntireRow.Clear
.Cells(1, lastCol + 1).Resize(1, Columns.Count - lastCol).EntireColumn.Clear
.UsedRange.Select
End With
'Save as .CSV file in the specific location stated earlier
'If there are errors in the code when Users presses 'No' for the conversion, set wks to nothing and end the process
On Error GoTo err_handler
wks.SaveAs Filename:=sFilename, FileFormat:=xlCSV
'System to/not display alerts to notify Users that they are replacing an existing file.
Application.DisplayAlerts = True
'Notify users that the .CSV file has been saved
MsgBox sFilename & " saved"
'Opens the CSV file in a specifc location in Notepad
MyTextFile = Shell("C:\Windows\notepad.exe ActiveWorkbook.Path & /S /K ""\newwb.csv""", vbNormalFocus)
err_handler:
'Set Wks to its default value
Set wks = Nothing
End Sub
编辑:
Application.ActiveWorkbook.Path 在线工作:
sFilename = Application.ActiveWorkbook.Path & "\newwb.csv"
但是有错误说系统在这一行找不到路径:
MyTextFile = Shell("C:\Windows\notepad.exe Application.ActiveWorkbook.Path & /S /K ""\newwb.csv""", vbNormalFocus)
【问题讨论】:
-
Set wks = ActiveWorkbook.ActiveSheet工作正常吗? -
嗨@iDevlop,是的,代码可以在newwb.xlsx中正常运行。唯一的问题是路径名。
-
然后试试
wks.Parent.FullName? -
有效!但是保存后我无法打开文件。 (请参阅我在原始问题中的编辑)谢谢!
-
使用
sFileName而不是重新计算名称!!这就是变量的用途。