使用 Excel VBA 添加下一个或上一个字母

Add next or previous letter with Excel VBA

我有这样的数据集

并且我想将每一行复制两次并在“代码”列中添加下一个或上一个字母。我能够实现第一个目标(每行重复两次)但我坚持在“代码”列中添加下一个或上一个字母。

这是我所做的:

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

我明白了

但我想得到这个:

一些帮助将不胜感激

你已经很接近了,只需要添加一行。

您可以使用 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

我会执行以下操作:将原始范围复制到 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