簡體   English   中英

EXCEL VBA取代了細胞的內容

[英]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

你需要:

  • 分別測試Q19BL23
  • 使用.Value而不是.Text,因為.Text是只讀的

編輯#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM