Search code examples
excelvbasavexlsx

Saving Cells from One Worksheet to a worksheet in a diff workbook -- having it save without prompt


Quick question.

I have this macro here, which has the functionality I Need (saves 2 cells from one worksheet in a workbook, to a worksheet in a different workbook.

The only issue I have is it keeps prompting for saving the file, and won't let me actually save it.

Any thoughts on what snippet of code I need to add to resolve? It appears it's opening the file as readonly, and maybe that's the issue?

Sub Test()
Dim x As Workbook
Dim y As Workbook
Dim vals As Variant

'## Open both workbooks first:
Set x = Workbooks.Open("C:/File.xlsx")
Set y = ThisWorkbook

'Store the value in a variable:
vals = y.Sheets("List").Range("B3:B4").Value

'Use the variable to assign a value to the other file/sheet:
x.Sheets("P1").Range("A1:A2").Value = vals

'Close x:
x.Close

End Sub

Solution

  • I've tested this and it works without an alert message. Just edit the file path in the open and save statements

    Option Explicit
    
    Sub Test()
    Dim x As Workbook
    Dim y As Workbook
    Dim vals As Variant
    
    '## Open both workbooks first:
    Set x = Workbooks.Open("C:\Test.xlsx")
    Set y = ThisWorkbook
    
    'Store the value in a variable:
    vals = y.Sheets("List").Range("B3:B4").Value
    
    'Use the variable to assign a value to the other file/sheet:
    x.Sheets("P1").Range("A1:A2").Value = vals
    
    'Turns off Alerts
    Application.DisplayAlerts = False
    
    'Saves file with changes
    x.SaveAs Filename:="C:\Test.xlsx", FileFormat:=51, CreateBackup:=False, AccessMode:=xlExclusive, _
    ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
    
    'Close x:
    x.Close
    
    'turns alerts back on
    Application.DisplayAlerts = True
    
    End Sub