我正在编辑一些由其他人编写的代码,我的Excel宏经验非常少。我试图在代码完成后将文件保存到网络位置。制作此程序的人将其保存到错误的位置,并且没有检查文件夹是否存在。
这是我目前用于抓取文件格式化的内容......
需要从此位置获取变量文件名& MA& .txt ... C:\ Twist Check Vaules \& MS& &安培; MP&安培; \ $ MA%的.txt
例如,如果MS = TEST且MP = GO且MA = A则... C:\ Twist检查Vaules \ TEST GO \ A.txt
[格式文件]
然后在最后它需要检查是否已经存在一个与上述变量同名的文件夹,但是在一个单独的位置......
实施例。检查此文件夹... ○:\ DIAPH \ SDATA \ Blinglet \&安培; MS&安培; &安培; MP&安培;
例如,如果MS = TEST且MP = GO ... O:\ diaph \ sdata \ Blinglet \ TEST GO
如果此文件夹存在,则需要继续前进,否则需要创建它。
最后,文件名为$ MA $ .txt或使用示例,A.txt需要保存在该位置......
O:\ diaph \ sdata \ Blinglet \ TEST GO
我试着自己查看,但是因为我对excel宏这么新,所以我遇到了很多麻烦。任何帮助将不胜感激!
Sub Polywork_Formating_Macro()
MsgBox ("Polyworks Data Formatting: Autostart Macro in Excel")
Dim idx As Integer
Dim fpath As String
Dim fname As String
Dim MS As String
Dim FileTitle As String
Dim MP As String
Dim MA As String
Dim question As Variant
MS = InputBox("Enter Shop Order:", "File Name")
MP = InputBox("Enter Job Number:", "File Name")
MA = InputBox("Enter A, B , or 360:", "File Name")
FileTitle = " " & MA & ".xls"
idx = 0
fpath = "C:\Twist Check Values\" & MS & "\" & MP & "\" & MA & "\"
fname = Dir(fpath & "*.txt")
While (Len(fname) > 0)
idx = idx + 1
Sheets.Add.Name = fname`enter code here`
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
& fpath & fname, Destination:=Range("A2"))
.Name = "a" & idx
[ 中间删除中的格式代码 ]
ActiveWorkbook.SaveAs Filename:="O:\diaph\sdata\Blinglet\" & MS & "\" & MP & "\" & FileTitle & ""
question = MsgBox("Are There AnyMore Files To Be Formated?", vbYesNo)
If question = vbYes Then
Workbooks.Open "C:\Stage Formatter.xlsm"
End If
End Sub
答案 0 :(得分:0)
对于文件路径和名称,您需要在字符串周围加上双引号。
Dim strFilePath as string
str = "C:\Twist Check Vaules\" & MS & MP & "\" & MA & ".txt
对于文件系统功能,您需要引用该库。在VBA IDE中,转到工具菜单并选择引用。选择" Microsoft脚本运行时"。
然后你可以声明一个filesystemobject。这可以用于文件夹和文件功能。
Dim fldr As Object
Dim strFolder as string
Dim fs As FileSystemObject
Set fs = New FileSystemObject
strFolder = "C:\Twist Check Vaules\" & MS & MP & "\"
If fs.FolderExists(strFolder) = true Then
'Do nothing
else
msbbox ("Folder is missing")
'or you can create it
Set fldr = fs.CreateFolder(strFolder)
If fldr Is Nothing Then
MsgBox "Could not create the folder"
End If
End if
对于您的文字文件:
Dim ts As TextStream
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)
ts.WriteLine "Whatever text you are writing to the file."
'Clean up
ts.Close: Set ts = Nothing
Set fs = Nothing