EXCEL VBAreplace单元格的内容
我想在满足条件的情况下replace单元格的文本,但数据位于另一个文件中。 我该怎么做? 我用了这样的东西:
Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) If targetSheet.Range("Q19", "BL23").Text = "OK" Then sourceSheet.Range("GB38", "GH38").Text = "Agreed" End If End Sub
你需要:
- 分别testingQ19和BL23
- 因为.Text是只读的,所以使用.Value而不是.Text
编辑#1:
这是我build议分开testing细胞的原因。 考虑:
Sub qwerty() MsgBox Range("C3,A1") = "X" End Sub
在一张空的工作表上,我们得到了False
如果我们将C3设置为X,则我们变为True
如果我们清除C3并将A1设置为X,我们会得到False !
事实certificate,对于一个分离的范围,只有第一个元素被检查……..其他人被忽略!
这里举一个例子,你可以通过条件来实现replace
''''' If targetSheet.[Q19, BL23].text= "ok" Then sourceSheet.Cells.Replace what:="Search string", replacement:="Replacement String" End If '''''
该单元格的内容不会更改为“同意”
这里是你更新的代码,但这不是标题中所写的replace
'''''' If targetSheet.[Q19, BL23].text = "OK" Then sourceSheet.[GB38, GH38].Value = "Agreed" End If '''''
用于validation多个范围内容使用.text
,但要在多个范围内插入值,则需要使用.value
testing下面的截图
使用.value
多范围validation的错误方法
没有指定范围属性的多范围validation的错误方法
使用.text
多范围validation的正确方法
尝试添加
customerWorkbook.Close customerWorkbook.Saved = True
在你的End Sub
语句之前。 这应该解决它。
得到它了! 感谢您的支持
Sub test() Dim customerBook As Workbook Dim filter As String Dim caption As String Dim customerFilename As String Dim customerWorkbook As Workbook Dim targetWorkbook As Workbook Set targetWorkbook = Application.ActiveWorkbook filter = "Text files (*.xlsx),*.xlsx" caption = "Please Select an input file " customerFilename = Application.GetOpenFilename(filter, , caption) Set customerWorkbook = Application.Workbooks.Open(customerFilename) Dim targetSheet As Worksheet Set targetSheet = targetWorkbook.Worksheets(1) Dim sourceSheet As Worksheet Set sourceSheet = customerWorkbook.Worksheets(1) Dim x As String If sourceSheet.Range("Q19").Text = "OK" Then x = "Agreed" End If targetSheet.Range("GB38", "GH38") = x End Sub