[英]EXCEL VBA replacing cell's content
我想在滿足條件的情況下替換單元格的文本,但數據在另一個文件中。 我該怎么做? 我使用過這樣的東西:
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
你需要:
編輯#1:
這就是我建議分別測試細胞的原因。 考慮:
Sub qwerty()
MsgBox Range("C3,A1") = "X"
End Sub
在空工作表上,我們得到False
如果我們將C3設置為X,我們就會得到True
如果我們清除C3並將A1設置為X,我們會得到假 !
事實證明,對於一個脫離范圍,只檢查第一個元素........其他元素被忽略了!
這里舉例說明如何通過條件實現替換
'''''
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
多范圍驗證的錯誤方法
沒有指定范圍屬性的多范圍驗證的錯誤方式
使用.text
多范圍驗證的正確方法
嘗試添加
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.