VBA 处理I列非空单元格,判断¥符号前后是否有数据,如果¥符号之后无数据则删除改符号,否则将¥替换为换行符
时间: 2023-09-19 12:05:09 浏览: 231
### 回答1:
你可以使用以下VBA代码来实现:
```vb
Sub ProcessI()
Dim cell As Range
Dim text As String
Dim pos As Integer
For Each cell In Range("I:I").SpecialCells(xlCellTypeConstants, xlTextValues)
text = cell.Value
pos = InStr(text, "¥")
If pos > 0 Then
If pos < Len(text) Then
cell.Value = Replace(text, "¥", vbNewLine)
Else
cell.Value = Left(text, pos - 1)
End If
End If
Next cell
End Sub
```
这个代码将遍历工作表中 I 列中所有非空单元格,检查其中的文本是否包含¥符号,并在符合条件的情况下进行相应的操作。如果¥符号之后有数据,则将¥替换为换行符;否则删除该符号。
### 回答2:
对于VBA处理I列非空单元格,并判断¥符号前后是否有数据的需求,可以使用以下代码实现:
```vba
Sub ProcessData()
Dim lastRow As Long
Dim cell As Range
lastRow = Cells(Rows.Count, "I").End(xlUp).Row '获取I列最后一行的行号
For Each cell In Range("I1:I" & lastRow) '遍历I列的每个单元格
If Not IsEmpty(cell) Then '判断单元格是否非空
Dim value As String
value = Trim(cell.Value) '去除单元格中的空格
If InStr(value, "¥") > 0 Then '判断单元格中是否存在¥符号
Dim index As Integer
index = InStr(value, "¥") '获取¥符号的位置
If index = Len(value) Then '判断¥符号是否位于单元格值的末尾
cell.Value = Left(value, index - 1) '删除末尾的¥符号
Else
cell.Value = Replace(value, "¥", vbCrLf) '将¥替换为换行符
End If
End If
End If
Next cell
End Sub
```
以上代码首先获取I列的最后一行行号,然后使用循环遍历I列的每个非空单元格。在循环中,通过使用`InStr`函数判断单元格中是否存在¥符号,并获取¥符号的位置。根据位置信息,可以判断¥符号前后是否有数据。如果¥符号位于单元格值的末尾,则使用`Left`函数删除末尾的¥符号;如果¥符号位于其他位置,则使用`Replace`函数将¥替换为换行符。最后,将修改后的值赋回原单元格,完成处理。
### 回答3:
VBA可以通过以下代码处理I列的非空单元格,判断其¥符号前后是否有数据,并根据条件进行相应操作,删除该符号或将¥替换为换行符。
```VBA
Sub ProcessIColumn()
Dim i As Integer
Dim rng As Range
Dim cell As Range
Dim cellValue As String
'设置I列范围
Set rng = Range("I1:I" & Cells(Rows.Count, 9).End(xlUp).Row)
'循环遍历I列的每个非空单元格
For Each cell In rng
If Not IsEmpty(cell) Then
cellValue = cell.Value
'判断¥符号前后是否有数据
If InStr(1, cellValue, "¥") <> 0 Then '存在¥符号
If InStr(1, cellValue, "¥") < Len(cellValue) Then '¥符号之后有数据
'将¥替换为换行符
cell.Value = Replace(cellValue, "¥", vbCrLf)
Else '¥符号之后无数据
'删除该符号
cell.Value = Replace(cellValue, "¥", "")
End If
End If
End If
Next cell
'释放对象
Set rng = Nothing
Set cell = Nothing
End Sub
```
以上代码首先设置I列的范围,然后循环遍历每个非空单元格。在判断¥符号前后是否有数据时,使用了InStr函数来搜索符号的位置。如果存在¥符号且位于字符串最后,则删除该符号;如果¥符号之后有数据,则将¥替换为换行符。最后,释放相关对象以释放内存。
阅读全文
相关推荐


















