我需要在excel中创建一个VBA脚本,它将订单号从前面的“CD”调到最后的“CD”,从“CD00001”到“00001CD”
任何帮助都会很棒。所有订单号都在B栏中,从第5行开始。请帮助。
到目前为止:
Private Sub OrderNumber_Click()
Dim Val As String
Dim EndC As Integer
EndC = Worksheets("Raw Data Upload").Range("A1048576").End(xlUp).Row
For i = 5 To EndC
Val = Right("B" & i, Len("B" & i) - 2) & Left("B" & i, 2)
Range("B" & i).Value = Val
Next
End Sub
这会将订单号替换为B5,B6等,但如果我将此功能放入Excel本身就可以正常工作。
答案 0 :(得分:1)
喜欢这个?你想要它在B栏吗?
Option Explicit
Private Sub OrderNumber_Click()
Dim i As Long
Dim val As String
Dim EndC As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Raw Data Upload")
EndC = ws.Range("A1048576").End(xlUp).Row
For i = 5 To EndC
val = ws.Cells(i, "A")
Range("B" & i).Value = Mid$(val, 3, Len(val) - 2) & Left$(val, 2)
Next i
End Sub
答案 1 :(得分:1)
dim beginStr, endStr, originalStr, outputStr as string
dim rng as range
'put the below into a loop, assigning a rng to the desired cell each time
originalStr = rng.value ' Change to chosen range
beginStr = left(originalStr,2)
endStr = right(originalStr, len(originalStr) - 2)
outputStr = endStr + beginStr
Range("B" & i).Value = outputStr
我还没有获得Excel的副本来测试它,但它应该可以工作。
答案 2 :(得分:0)
只需使用:
Right(Range("B" & i), Len(Range("B" & i)) - 2) & Left(Range("B" & i), 2)
另一种方法是将单元格设置为Range()
:
Sub t()
Dim cel As Range
Dim endC As Long
endC = Worksheets("Raw Data Upload").Range("A1048576").End(xlUp).Row
For i = 5 To endC
Set cel = Range("B" & i)
myVal = Right(cel, Len(cel) - 2) & Left(cel, 2)
Range("B" & i).Value = myVal
Next
End Sub
目前,当您执行Right("B" & i, Len("B" & i) - 2) & Left("B" & i, 2)
时,对于第5行,这将变为Right("B5", Len("B5") - 2) & Left("B5", 2)
,然后评估为:
Right("B5",0) & Left("B5",2)
,是
[nothing] & B5
,终于成为了
B5
请注意,缺少使用B5
作为范围。相反,它被视为一个字符串。
(另外,我假设这是在ActiveSheet
上运行。如果没有,请在范围之前添加工作表,即Worksheets("Raw Data Upload").Range("B" & i)...
)
答案 3 :(得分:0)
试试这个
Private Sub OrderNumber_Click()
Dim cell As Range
With Worksheets("Raw Data Upload")
For Each cell in .Range("B5", .Cells(.Rows.Count, 2).End(xlUp))
cell.Value = Right(cell.Value, Len(cell.Value) - 2) & Left(cell.Value, 2)
Next
End With
End Sub