
我是全新的,不確定我問的是否正確。我有一個 Excel 電子表格,我想與客戶分享,以便我們可以編輯和更新其資訊。但是,我只想共享一個部分,或者也許只是一個工作表,因為我在那裡有多個不屬於他的不同帳戶。我不想更新和編輯兩個單獨的工作簿。我希望做的是在我與他共享的工作簿和我當前的工作簿之間創建一個雙向鏈接,這樣當其中一個工作簿發生更改時,它會自動更新另一個工作簿,反之亦然。
之前的一篇文章幫助我在工作表之間做到了這一點,我喜歡它(感謝 Christofer Weber,它效果很好)。我知道它需要 VBA,但我只是不明白。有任何想法嗎?我只是希望修改目前用於工作表的 VBA。
當前的一個
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range(Target.Address), Range("A2:D5")) Is Nothing Then
Application.EnableEvents = False
Sheets(1).Range(Target.Address).Value = Target
Sheets(2).Range(Target.Address).Value = Target
Sheets(3).Range(Target.Address).Value = Target
Application.EnableEvents = True
End If
End Sub
這是我到目前為止所擁有的,但我知道頂行不正確。
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect(Range(Target.Address), Range("A2:D5")) Is Nothing Then
Application.EnableEvents = False
Workbooks("Test excel workbook 1 - macro.xlsm").Sheets(1).Range(Target.Address).Value = Target
Workbooks("Test excel workbook 2 - macro.xlsm").Sheets(1).Range(Target.Address).Value = Target
Application.EnableEvents = True
End If
End Sub
答案1
我已經對此進行了測試,我認為這應該足以幫助您。但這裡有一些我注意到的事情。
首先要注意的是,Intersect
如果您要比較不同工作表中的範圍,則該方法不起作用這個問題。您在這裡沒有明確地這樣做,但我認為指定您正在使用哪個工作表而不是讓 VBA 為您隱式決定是明智的。
第二件事是以此行為例:
Workbooks("Test excel workbook 1 - macro.xlsm").Sheets(1).Range(Target.Address).Value = Target
我個人認為將一個範圍的值設為另一個範圍而不是將其設為價值另一個範圍的,看起來像這樣:
Workbooks("Test excel workbook 1 - macro.xlsm").Sheets(1).Range(Target.Address).Value = Target.Value
這是我想出來的程式碼:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const filePath As String = "C:\some\file\path\otherthing.xlsm"
Dim otherwb As Workbook
Dim otherws As Worksheet
Dim thisws As Worksheet
Dim rangeIntersection As Range
'this will allow opening the other workbook without
'displaying the white UI
Application.ScreenUpdating = False
'setting a reference to this worksheet
Set thisws = ThisWorkbook.Worksheets("Sheet1")
'opens an unopened workbook or it will simply set a reference
'to this workbook if it's already opened
Set otherwb = Excel.Workbooks.Open(filePath)
'just chose a random worksheet
Set otherws = otherwb.Worksheets(1)
'doing the intersection
Set rangeIntersection = _
Application.Intersect(Range(Target.Address), _
thisws.Range("A2:D5"))
If Not rangeIntersection Is Nothing Then
Application.EnableEvents = False
otherws.Range(Target.Address).Value = Target.Value
Application.EnableEvents = True
End If
'uncomment this if you do want to close the wb at the end
' otherwb.Save
' otherwb.Close
Application.ScreenUpdating = True
End Sub
希望能幫助你