Excel 输出范围与输入范围相同
我曾经使用VBA,但似乎找不到解决这个问题的方法。我找到了一个迭代过程来选择一个单元格,执行一个过程,然后选择下一个单元格并再次执行该过程,直到NULL。我在将每个流程解决方案输出到下一列时遇到问题。以下是我所拥有的:Excel 输出范围与输入范围相同,excel,vba,range,Excel,Vba,Range,我曾经使用VBA,但似乎找不到解决这个问题的方法。我找到了一个迭代过程来选择一个单元格,执行一个过程,然后选择下一个单元格并再次执行该过程,直到NULL。我在将每个流程解决方案输出到下一列时遇到问题。以下是我所拥有的: Sub Name () Dim X As Integer Dim MyString as String Application.ScreenUpdating = False NumRows = Range("D2", Range("D2").End(xlDown)).Rows
Sub Name ()
Dim X As Integer
Dim MyString as String
Application.ScreenUpdating = False
NumRows = Range("D2", Range("D2").End(xlDown)).Rows.Count
Range("D2").Select
For X = 1 To NumRows
MyString = ActiveCell.Value
MyString = Right(MyString, Len(MyString)-6)
Range("I2 to I#").Value = MyString
ActiveCell.Offset(1,0).Select
Next X
End Sub
Range(“I2到I#”)。Value=MyString
是我需要帮助的行。我需要它增加到I3、I4、I5等,直到达到NumRows计数。处理单元格时,最好的循环方式是对范围内的每个单元格进行,
,因此,根据注释,避免选择,这将有助于您:
Option Explicit
Sub Name()
Dim C As Range, MyRange As Range
Dim LastRow As Long
Application.ScreenUpdating = False
With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your working sheet name
LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row 'last row on column D
Set MyRange = .Range("D2:D" & LastRow) 'declare your working range
For Each C In MyRange
If Not C = vbNullString Then .Cells(C.Row, "I") = Right(C, Len(C) - 6)
Next C
End With
Application.ScreenUpdating = True
End Sub
另一个解决方案是
Do-Until
。如果数据中间没有空单元格,则可以使用此方法。
Option Explicit
Sub Test()
Dim StartingPoint As Long
StartingPoint = 2 'Set the line to begin
With ThisWorkbook.Worksheets("Sheet1") 'Set the worksheet
Do Until .Cells(StartingPoint, "D").Value = "" 'Repeat the process until you find empty cell
.Cells(StartingPoint, "I").Value = Right(.Cells(StartingPoint, "D").Value, Len(.Cells(StartingPoint, "D").Value) - 6)
StartingPoint = StartingPoint + 1
Loop
End With
End Sub
请阅读并避免
integer
变量,您可能要存储的值可能大于integer
所能容纳的值。使用“选择”是否存在问题?所以使用Double更好?使用Long@Zman3。使用选择
和激活
会给您的代码带来很多麻烦。谢谢。这太棒了!您能解释一下“&”是如何工作的吗?它用于连接“Hello”和“World”
=HelloWorld
<代码>“D2:D”和LastRow=“D2:D100”
(如果LastRow=100
)。在Excel上的工作方式与在VBA上的工作方式相同。值得注意的是,在确定最后一行时存在差异。OP的方法将查找列中最后一个非空白单元格,而Damian的方法将查找列中最后一个真正填充的单元格,不考虑任何空白中间单元格可能是一个愚蠢的问题,但为什么不能使用“D2:DLastRow”?VBA处理变量,因为VBALastRow=100
,但“D2:DLastRow”
=“D2:DLastRow”
。双引号之间的任何内容都表示字符串
,vba不会处理变量LastRow
,而是尝试处理整个字符串,从而导致错误。