首页 > 解决方案 > 如何使用 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 中只得到一些字符?谢谢您的回答。我检查了几个帖子,但我找不到解决方案。

标签: excelvbasavecharacterfilenames

解决方案


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)


推荐阅读