简体   繁体   English

Excel VBA宏 - 在选定的单元格上运行

[英]Excel VBA Macro - Run on Selected Cells

I am a complete novice when it comes to writing in VBA and have been searching for an answer I could use to fix my problem with no luck. 在VBA写作时,我是一个完整的新手,并且一直在寻找一个我可以用来解决我的问题而没有运气的答案。 I've seen some related questions but nothing I've been able to apply. 我已经看到了一些相关的问题,但我没有能够申请。

I have a recorded macro that simply adds a leading 0 to a number by using a concatenate function. 我有一个录制的宏,只需使用连接函数将前导0添加到数字。 I am using Relative References so that the macro will run on whichever cell is selected in column A. This works if I want to add a leading zero to each cell one-by-one. 我正在使用相对引用,以便宏将在列A中选择的任何单元格上运行。如果我想逐个向每个单元格添加前导零,则此方法有效。 However, I would like to be able to simply select the cells in column AI want to add a leading 0 to and then run the macro on all the selected cells at once. 但是,我希望能够简单地选择列AI中的单元格想要添加前导0,然后立即在所有选定单元格上运行宏。 Any help is greatly appreciated! 任何帮助是极大的赞赏!

Sub leadingzerotake2()
 ActiveCell.Offset(0, 10).Range("A1").Select
 ActiveCell.FormulaR1C1 = "=CONCATENATE(""0"",RC[-10])"
 ActiveCell.Select
 Selection.Copy
 ActiveCell.Offset(0, -10).Range("A1").Select
 Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
 ActiveCell.Offset(0, 10).Range("A1").Select
 Application.CutCopyMode = False
 Selection.ClearContents
 ActiveCell.Offset(0, -10).Range("A1").Select
End Sub

Thank you!!! 谢谢!!!

Simply put this code in the worksheet module - 只需将此代码放在工作表模块中 -

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Column = 1 And Target.Count < 1000 Then
        For Each cell In Target.Cells
            'run your fuction here
        Next
    End If
End Sub

Since this function can potentially run a really long time, I've limited this operation to a max of 1000 cells selection. 由于此功能可能会运行很长时间,因此我将此操作限制为最多1000个单元格选择。 you can remove this part if you'd like. 如果您愿意,可以删除此部分。

BTW, If you simply want to add a leading zero to the content of the selected cell, I would put - 顺便说一句,如果您只想在所选单元格的内容中添加前导零,我会 -

cell.Value = "0" & cell.Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM