尝试在Excel中更改单元格中的文本

我十年来一直没有在Excel中使用过VBA,但是想要find一种编码解决scheme来改变20K以上的一些文本。 我的工作让我手动做,但我知道必须有一个Comp Sci解决scheme。

我已经整理了需要更改的列。 还有成千上万的重复项需要改变,如下面的例子所示

例如:1001.tif如果是第一个重复则更改为1001_1.tif,如果是该值的第一个文本则将其保留。

我下面的代码根本不起作用,但应该是它的框架。

Sub Button1_Click() Dim n As Integer n = 1 Dim test As String test = Cells(1, D).Text Dim active As String active = Cells(2, D).Text For i = 2 To 12 active = Cells(i, D) If active = test Then Cells(i, D).Text = Microsoft.VisualBasic.Strings.Left(test, 4) + "_" + n + ".tif" n = n + 1 Else test = active End If Next i Cells(1, a).Text = "Done" End Sub 

有小费吗?

如果你对vba有一些厌恶,这里是一个实现,作为与当前vba答案相同方法的in-cell公式。 假设D是文件名的列:

=(IF,(D,D,D),D,D,D) .tif“,D2)也会这样做。

一些解释:COUNTIF()公式计算从列顶部($ D $ 2)到当前行的string出现次数。 MID / FIND公式将出现次数和下划线放在之前的位置。 在文件名中。 FIND获取。的位置,MID在点之前切断string,然后公式的其余部分附加数字和文件扩展名。 这将适用于超过4个字符的数字。

使用COUNTIF():

 Sub Button1_click() Dim i As Long Dim j As Long For i = 2 To 12 With ActiveSheet j = Application.WorksheetFunction.CountIf(.Range(.Cells(1, 4), .Cells(i - 1, 4)), Left(.Cells(i, 4), Len(.Cells(i, 4)) - 4) & "*") If j > 0 Then .Cells(i, 4).Value = Replace(.Cells(i, 4), ".tif", "_" & j & ".tif") End If End With Next i 

变成这样:

在这里输入图像说明

成:

在这里输入图像说明

我已经根据你的意思做了一些假设,对你的代码做了一些修改。 希望这会有所帮助。

 Sub Button1_Click() Dim n As Integer Dim test As String Dim active As String n = 1 For i = 2 To 12 active = Cells(i, 4) test = Cells(i - 1, 4) If active = test Then Cells(i, 4).Value = VBA.Left(test, 4) & "_" & n & ".tif" n = n + 1 Else test = active n = 1 End If Next i Cells(1, 1).Value = "Done" End Sub 

这段代码将按照你所描述的进行。 只要对所有相同的文件进行sorting并运行macros。 我添加了rg来计算以前是dynamic的行,但是您可以将其更改为您的需要。

  Sub test() Dim n As Integer Dim rg As Integer rg = ActiveSheet.UsedRange.Rows.Count n = 1 Dim test As String test = Cells(1, 4).Text Dim active As String For i = 2 To rg active = Cells(i, 4) If active = test Then Cells(i, 4).Value = Left(test, 4) & "_" & n & ".tif" n = n + 1 End If Next i MsgBox "Done" End Sub 

看看下面所做的更改。 我认为这是你想要完成的。

 Sub Button1_Click() Dim n As Integer Dim test As String, active As String n = 1 For i = 2 To 12 active = Cells(i, D).Value2 If active = test Then Cells(i, "D").Value2 = Left(test, 4) & "_" & n & ".tif" n = n + 1 Else test = active End If Next i Cells(1, "A").Value2 = "Done" End Sub