如果在某个单元格(VBA)中存在“ – ”,则复制到macros

如果在某个单元格中存在“ – ”或“/”,我试图在同一个表格中复制一些单元格。

根据“ – ”或“/”的数量是要复制的次数。 这是我的代码,但它不工作,任何人都可以帮忙吗?

Sub TWB_Copy_columns() 'TWB_Copy_columns Macro Dim celltxt As String Range("B14").Select Selection.End(xlToRight).Select celltxt = Selection.Text If InStr(1, celltxt, "-") Or InStr(1, celltxt, "/") Then Range("BA5:BB36").Select Selection.Copy Range("BD5").Select ActiveSheet.Paste Range("BG5").Select End If End Sub 

看来你正在查看单元格内容的显示格式,以确定它是否是一个date。 有一个本地的VBAfunction, IsDate在真正的date做这个决定相当好。 如果你的数据不包含date作为真正的date,那么他们应该是真实的date,这是另一个需要解决的问题。

 with worksheets("sheet1") if isdate(.cells(14, "B").end(xltoright)) then .range("BA5:BB36").copy destination:=.range("BD5") end if end with 

在我看来,如果BA5:BB36不是静态的,但是你没有提供什么决定位置的指示,这个代码是可重用的。 这可能是数据块中最后两列的数据,但这只是一个猜测。

这是重构和固定的版本:

 Sub TWB_Copy_columns() 'TWB_Copy_columns Macro 'Range("B14").Select 'Selection.End(xlToRight).Select 'celltxt = Selection.Text ' Use explicit references and avoid select. In this case, you will need to ' qualify the workbook and sheetname of the range you are using. We can then ' directly access the value of that range. ' Also, no need to declare a string just to hold onto the value. Directly use the value instead With ThisWorkbook.Sheets("Sheetname") If InStr(1, .Range("B14").End(xlToRight).value, "-") > 0 Or InStr(1, .Range("B14").End(xlToRight).value, "/") > 0 Then .Range("BD5:BB36").value = .Range("BA5:BB36").value End If End With End Sub 

首先,总是避免SelectActivate 。 在这种情况下,我直接分配值而不是尝试复制,粘贴或select。 任何时候你看到Range("A5").Select; Selection.Value Range("A5").Select; Selection.Value你真的需要Range("A5").Value 。 同样,从来没有一个不合格的范围。 Range("A5")与说ActiveSheet.Range("A5")相同,如果错误的工作表处于活动状态,会使事情变得复杂。

最后,如果你真的使用一个variables进行比较,请使用直接值。 没有必要为一项任务创build一个variables(至less在我看来)。

编辑:

正如拉尔夫所build议的,请考虑阅读以下主题: 如何避免在Excel VBAmacros中使用select 。 一旦你学会避免Select你的能力会飞涨。

这就是我所想要的(对于每一个“ – ”或“/”,复制Range("BA5:BB36")并将其粘贴到Range("BD5")Range("BG5") -空间在您的专栏):

 Sub TWB_Copy_columns() 'TWB_Copy_columns Macro Dim celltxt As String Dim vWords As Variant Dim rFind As Range Dim i As Long celltxt = Range("B14").Value celltxt = Replace(celltxt, "-", "/") vWords = Split(celltxt, "/") Range("BA5:BB36").Copy Range("BD5").Activate For i = 1 To UBound(vWords) ActiveCell.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ActiveCell.Offset(0, 2).Activate Next End Sub