如何使用以下excel vba代码?

Sub MergeRanges() Dim rng As Range, txt As String For Each rng In Selection txt = txt & rng.Value2 Next Application.DisplayAlerts = False Selection.Merge Selection = txt Application.DisplayAlerts = True End Sub 

当合并单元格时,我想保留单元格中的所有数据。 我GOOGLE了一些时间,find上面的代码。 但我不知道如何使用它? 他们的意思是什么? 谢谢。

build立:

  1. 打开VBA编辑器(工具>macros> Visual Basic编辑器)(快捷键AltF11
  2. 插入>模块
  3. 将代码粘贴到您的新模块中。

使用:

  1. select您要合并的单元格。
  2. 工具>macros>macros…(快捷键AltF8 )>selectMergeRanges >运行

如果您希望macros使用“特殊格式”(如date),则应将.Value2更改为.Text

  • 在Excel中,按Alt-F8

  • 使用对话框添加一个空的macros“MergeRanges”

  • 在上面添加你的代码。

  • 要运行代码,请select一些要合并的单元格,再次按Alt-F8并运行该macros。

突出显示您要合并(不是date或货币)的一些单元格,然后按Alt + F8select此macros。 它应该(我没有testing)将单元格内容合并到一个单元格中,而不会丢失每个单元格中的任何内容。

确保先在文件中插入代码,按Alt + F11打开VBE,右键单击资源pipe理器,然后select添加模块。 然后粘贴此代码。确保您的macros安全性足够低,可以运行它。