excel - 如何在VB中替换字符串?
问题描述
尝试替换字符串时出现问题
tmpStr = "['common_follow'] = '#1' " & vbCr _
& "['common_cancel'] = '#10' "
For i = 1 To rng.Rows.Count
cellValue = rng.Cells(i, 4).Value
'Debug.Print (cellValue)
tmp = "#" & i
'Debug.Print (tmp)
tmpStr = Replace(tmpStr, tmp, cellValue)
Debug.Print (tmpStr)
Next i
#1
替换为['common_follow'] = 'follow
' => 好
#10
替换为['common_cancel'] = 'follow0'
=>#10
无法识别替换 ->#1
仅识别
你怎么处理这个?
解决方案
先更换#10
再#1
解决问题。
因此向后循环:
Dim TmpStr As String
TmpStr = "['common_follow'] = '#1' " & vbCr _
& "['common_cancel'] = '#10' "
Dim i As Long
For i = Rng.Rows.Count To 1 Step -1 'backwards
Dim CellValue As Variant
CellValue = Rng.Cells(i, 4).Value
'Debug.Print CellValue
Dim Tmp As String
Tmp = "#" & i
'Debug.Print Tmp
TmpStr = Replace$(TmpStr, Tmp, CellValue)
Debug.Print TmpStr
Next i
或者,您需要替换包括周围的单引号' '
Dim TmpStr As String
TmpStr = "['common_follow'] = '#1' " & vbCr _
& "['common_cancel'] = '#10' "
Dim i As Long
For i = 1 To Rng.Rows.Count 'forward
Dim CellValue As Variant
CellValue = Rng.Cells(i, 4).Value
'Debug.Print CellValue
Dim Tmp As String
Tmp = "'#" & i & "'" 'replace with quotes '#1'
'Debug.Print Tmp
TmpStr = Replace$(TmpStr, Tmp, "'" & CellValue & "'") 'add quotes to the value
Debug.Print TmpStr
Next i
推荐阅读
- javascript - 如何生成和共享文件?
- r - 如何编写一个函数来循环变量并使用ggplot绘图
- python - 将从文件读取的整数或浮点数列表转换为 numpy 数组
- c++ - 如何在 C++ 中将“%Y%m%d”格式字符串转换为 time_t 变量?
- c++ - C++ 字符串单个字符
- jquery - jQuery - 如果值与数组中的元素匹配,则禁用复选框
- json - Instagram JSON 导出。使用 OPENJSON 透视子数组
- google-cloud-platform - Google Cloud Platform - 数据流无法写入错误表
- node.js - 从 mongodb 坐标在传单地图上放置一个标记
- office-addins - Web 加载项在浏览器 Outlook 机器人中加载,而不是本机桌面 Outlook