Ken*_*nny 3 variables excel vba path
这是我在这个网站上的第二篇文章,我对 VBA 比较陌生。
我今天的问题是,
如何将单元格值添加到路径字符串以指定要保存工作簿的文件夹。
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Path = "D:\folder1\folder2\Projects\The FILES\theFILES\"FileName1"\
FileName1 = Range("B6")
FileName2 = Range("A1")
ActiveWorkbook.SaveAs Filename:=Path & FileName2 & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Run Code Online (Sandbox Code Playgroud)
提前致谢!
回答所述问题
Path = "D:\folder1\folder2\Projects\The FILES\theFILES\" & FileName1 & "\"
Run Code Online (Sandbox Code Playgroud)
另请参阅其他反馈和更正代码以获取其他反馈。
回答的长解释
当你给一个字符串变量赋值时,最常见的方法是这样的:
string = "This is my string value."
Run Code Online (Sandbox Code Playgroud)
但是,您可能经常在代码中看到具有相当长字符串的语法,例如以下代码中的语法,以允许所有文本适合开发屏幕而无需滚动:
string = "This is my really, really, really long string value. I am making this " _
& "as long as I can, while also having something to write."
Run Code Online (Sandbox Code Playgroud)
如果删除_, 并将所有内容移到一行,它将如下所示:
string = "This is my really, really, really long string value. I am making this " & "as long as I can, while also having something to write."
Run Code Online (Sandbox Code Playgroud)
请注意,分配给变量的任何字符串都可以按以下方式分解:
string = "This is" & " my " & "string value."
' Returns the same result as:
string = "This is my string value."
Run Code Online (Sandbox Code Playgroud)
此外,如果我有一个字符串变量 ,str_val = " my "那么我可以使用替换将上面的示例写为:
string = "This is" & str_val & "string value."
Run Code Online (Sandbox Code Playgroud)
其他反馈
目前,您的代码顺序(请参阅下面的原始代码)是:
不幸的是,遵循此顺序意味着在步骤 2) 中, 的值为FileName1空字符串"",因为尚未为其分配值。
因此,您应该遵循的顺序是:
字符串中的附加变量
@Davesexcel 临时发布了一个答案(然后更改),它假定您的字符串中的folder1和folder2也是变量。如果确实如此,我附上了替代代码。
原始代码
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Path = "D:\folder1\folder2\Projects\The FILES\theFILES\"FileName1"\
FileName1 = Range("B6")
FileName2 = Range("A1")
ActiveWorkbook.SaveAs Filename:=Path & FileName2 & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Run Code Online (Sandbox Code Playgroud)
更正代码
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
FileName1 = Range("B6")
FileName2 = Range("A1")
Path = "D:\folder1\folder2\Projects\The FILES\theFILES\" & FileName1 & "\"
ActiveWorkbook.SaveAs Filename:=Path & FileName2 & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Run Code Online (Sandbox Code Playgroud)
替代代码
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
FileName1 = Range("B6")
FileName2 = Range("A1")
Path = "D:\" & folder1 & "\" & folder2 & "\Projects\The FILES\theFILES\" & FileName1 & "\"
ActiveWorkbook.SaveAs Filename:=Path & FileName2 & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Run Code Online (Sandbox Code Playgroud)