如何从 VBA 的单元格中获取一些字符

How can I get some characters from a cell with VBA

我正在尝试使用 vba 保存一个 excel 文件,我希望该文件的文件名是单元格 A3 中的一些字符。

假设我的单元格 A3 有下一个数字 2420561300,我希望我的文件名仅从该数字开始的前 6 个字符作为其名称:242056。

我有以下代码:

With Application.FileDialog(msoFileDialogSaveAs)
.Title = "Please choose where to save the file and a name to it"
.ButtonName = "Save Excel"
Set rng = Range("A3").Value
.InitialFileName = "C:\Users\admin\Desktop\" & rng
If .Show = 0 Then
    MsgBox "File was not saved.", vbCritical
    Exit Sub
End If

从这段代码中,我得到的文件名是整数,但是我怎样才能只从 Range().Value 中得到一些字符呢? 谢谢您的回答。我已经检查了几个帖子,但我找不到解决方案。

With Application.FileDialog(msoFileDialogSaveAs)
.Title = "Please choose where to save the file and a name to it"
.ButtonName = "Save Excel"
.InitialFileName = "C:\Users\admin\Desktop\" & Left(Range("A3").Value, 6)
If .Show = 0 Then
    MsgBox "File was not saved.", vbCritical
    Exit Sub
End If
End With

@FaneDuru 在评论中给了我正确答案,非常感谢。它只是添加 Left(Range("A3").Value, 6)

为了直接SaveAs一个工作簿,可以这样进行:

Dim fullFilename As String
fullFilename = "C:\Users\admin\Desktop\" & left(Range("A3").value, 6) & ".xlsx"
ActiveWorkbook.SaveAs fileName:=fullFilename, FileFormat:=xlWorkbookDefault

以上代码假定您的 Range("A3") 也不包含扩展名。如果包含,则必须删除 fullFilename 定义的最后一部分。

如果你非要用dialog,让它显示要保存的名字,请用: .InitialFileName = "C:\Users\admin\Desktop\" & Left(Range("A3").Value, 6) & ".xlsx"