EXCEL VBA取代了细胞的内容

时间:2015-05-22 13:51:48

标签: excel vba excel-vba

我想在满足条件的情况下替换单元格的文本,但数据在另一个文件中。我该怎么做? 我使用过这样的东西:

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

4 个答案:

答案 0 :(得分:4)

你需要:

  • 分别测试 Q19 BL23
  • 使用 .Value 而不是 .Text ,因为 .Text 是只读的

修改#1:

这就是我建议分别测试细胞的原因。考虑:

Sub qwerty()
   MsgBox Range("C3,A1") = "X"
End Sub

在空工作表中,我们得到错误
如果我们将 C3 设置为 X ,我们会得到 True < / strong>
如果我们清除 C3 并将 A1 设置为 X ,我们会收到错误!< / p>

事实证明,对于一个脱节范围,只检查第一个元素........忽略其他元素!

答案 1 :(得分:2)

这里是一个如何通过条件

实现替换的示例
'''''
If targetSheet.[Q19, BL23].text= "ok" Then
    sourceSheet.Cells.Replace what:="Search string", replacement:="Replacement String"
End If
'''''
  

单元格的内容不会更改为“同意”

这里是您更新的代码,但这不是标题

中的替换
''''''
If targetSheet.[Q19, BL23].text = "OK" Then
    sourceSheet.[GB38, GH38].Value = "Agreed"
End If
'''''

要验证多个范围内容的使用.text,但要在多个范围内插入值,您需要使用.value

在下面的屏幕截图中进行测试

使用.value

进行多重范围验证的错误方式

enter image description here

没有指定范围属性的多范围验证的错误方法

enter image description here

使用.text

进行多重范围验证的正确方法

enter image description here

答案 2 :(得分:1)

尝试添加

customerWorkbook.Close customerWorkbook.Saved = True
在您的End Sub声明之前

。那应该解决它。

答案 3 :(得分:0)

知道了!感谢您的支持

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