简体   繁体   中英

Debugging VBA copy range and saving using cell references as file name

I've researched a great bit on stackoverflow and mrexcel and a few other sites to come up with this. In short I have a template that I copy information into to combine with a few variables to create a text string that populates into a range that I've named 'export'. I would like for this range to be copied to a new workbook to be saved as a .txt file. However, I want the VBA to name and save the file to a predetermined location [t:\\downloads]. The file name should be a combination from two cells on the source sheet the account number (stored in cell c1) and the month/year (stored in cell b3). For example, if the account number in cell c1 is 123456 and the date in b3 is 12/25/2017, then I would like the filename to appear as t:\\downloads\\123456.2017.12.txt.

This is the code I have thus far:

Sub Foo_Tab()
  Dim wbSource As Workbook
  Dim wssource As Worksheet
  Dim wbdest As Workbook


'References
  Set wbSource = ActiveWorkbook
  Set wssource = ActiveSheet
  Set wbdest = Workbooks.Add
  acct = Cells("c1")
  yr = Year(Cells("b3"))
  mnth = Month(Cells("b3"))


'Copy range on original sheet
  wssource.Range("Export").Copy

'Save in new workbook
  wbdest.Worksheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
  Application.CutCopyMode = False

'get file name from cells
  Dim path As String
  Dim full As String
  Dim acct As String
  Dim yr As String
  Dim mnth As String
  path = "Z:\Downloads\"
  full = path + acct + "." + yr + "." + mnth + ".txt"
  ActiveWorkbook.SaveAs filename:=full
  wbdest.Close savechanges:=True

End Sub

Try to replace

ActiveWorbook.SaveAs filename:=full
wbdest.Close savechanges:=True 

with this (I assume that wbdest is active worbook; -4158 is for .txt format):

With wbdest
        .SaveAs full, FileFormat:=-4158
        .Close SaveChanges:=True
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM