使用 Excel VBA 添加下一个或上一个字母
Posted
技术标签:
【中文标题】使用 Excel VBA 添加下一个或上一个字母【英文标题】:Add next or previous letter with Excel VBA 【发布时间】:2021-12-05 14:55:21 【问题描述】:我有这样的数据集
我想将每一行复制两次,并在“代码”列中添加下一个或上一个字母。我能够实现第一个目标(将每行复制两次),但我坚持在“代码”列中添加下一个或上一个字母。
这就是我所做的:
Sub mysub()
Dim r As Range, n As Long, i As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws1, ws2 As Worksheet
Set ws1 = wb.Sheets("Sheet1")
Set ws2 = wb.Sheets("Sheet2")
Set r = ws1.Range("C3", ws1.Range("E" & Rows.Count).End(xlUp))
For i = 1 To r.Rows.Count
n = n + 1
ws2.Cells(n + 1, 1).Value = r.Cells(i, 1).Value
ws2.Cells(n + 1, 2).Value = r.Cells(i, 2).Value
ws2.Cells(n + 1, 3).Value = r.Cells(i, 3).Value
n = n + 1
ws2.Cells(n + 1, 1).Value = r.Cells(i, 1).Value
ws2.Cells(n + 1, 2).Value = r.Cells(i, 2).Value * -1
Next i
End Sub
我明白了
但我想得到这个:
我们将不胜感激
【问题讨论】:
负数会倒退?这些代码只是运行 A-Z 还是什么? @SJR 表示一行,如果值为“C”,则下一个值必须为“D”。反之亦然,对于一行,如果值为“D”,则下一个值必须为“C” 【参考方案1】:你已经很接近了,只需要添加一行。
您可以使用Resize
稍微缩短代码。
Sub mysub()
Dim r As Range, n As Long, i As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws1 As Worksheet, ws2 As Worksheet 'need to specify each
Set ws1 = wb.Sheets("Sheet1")
Set ws2 = wb.Sheets("Sheet2")
Set r = ws1.Range("C3", ws1.Range("C" & Rows.Count).End(xlUp))
For i = 1 To r.Rows.Count
n = n + 1
ws2.Cells(n + 1, 1).Resize(2, 2).Value = r.Cells(i, 1).Resize(, 2).Value
ws2.Cells(n + 1, 3).Value = r.Cells(i, 3).Value
n = n + 1
ws2.Cells(n + 1, 2).Value = r.Cells(i, 2).Value * -1
ws2.Cells(n + 1, 3).Value = IIf(r.Cells(i, 3) = "C", "D", "C") 'added
Next i
End Sub
【讨论】:
【参考方案2】:我会执行以下操作:将原始范围复制到 sheet2,然后向后循环并复制每一行并调整值。
这应该比单独处理每个单元格要快一些。您可以使用数组更快地获得它。
Option Explicit
Public Sub mysub()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws1 As Worksheet
Set ws1 = wb.Sheets("Sheet1")
Dim ws2 As Worksheet
Set ws2 = wb.Sheets("Sheet2")
Dim r As Range
Set r = ws1.Range("C3", ws1.Range("E" & Rows.Count).End(xlUp))
'copy from ws1 to ws2
ws2.Range("A2").Resize(r.Rows.Count, r.Columns.Count).Value = r.Value
'duplicate values: loop backwards when inserting or deleting
Dim i As Long
For i = r.Rows.Count To 1 Step -1
' duplicate row
ws2.Rows(i + 1).Copy
ws2.Rows(i + 1).Insert xlShiftDown
' adjust value *-1
ws2.Rows(i + 1).Cells(1, 2).Value = ws2.Rows(i + 1).Cells(1, 2).Value * -1
' adjust D/C
If ws2.Rows(i + 1).Cells(1, 3).Value = "D" Then
ws2.Rows(i + 1).Cells(1, 3).Value = "C"
Else
ws2.Rows(i + 1).Cells(1, 3).Value = "D"
End If
Next i
Application.CutCopyMode = False
End Sub
【讨论】:
以上是关于使用 Excel VBA 添加下一个或上一个字母的主要内容,如果未能解决你的问题,请参考以下文章