问题
I am looking to assign an input box string to a workbook name in order to manipulate data from one sheet to the next. For example, when I generate a report it is assigned a temporary file name "tmp1" "tmp2" etc. I would like to use another excel sheet as a program which will run a macro in order to sort, copy, etc. the newly generated file, with only having to enter the name of the temporary file "tmp1" etc.
I am able to run the macro that I need and am familiar with the 'With' statements that will allow me to do so. my issue is when I run the following code:
Sub MyMacro()
Dim wb As Workbook
Dim X As String
X = InputBox("Set work book name")
Set wb = Workbooks(X)
With Workbooks(x)
.'code is entered here'
End with
End sub
I run into an object error. It seems I am incorrectly referencing the new file. Any help would be appreciated
Thanks
回答1:
If you are attempting to create a new temporary workbook and assign a filename to it then try:
Sub MyMacro()
Dim X As String
X = InputBox("Set work book name")
Workbooks.Add
ActiveWorkbook.SaveAs Filename:="C:\Users\garys\Desktop\" & X & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
With ActiveWorkbook
'code is entered here'
End With
End Sub
(Of course, you would use your own folder-name and your file-type)
EDIT#1: specifically in your code, try replacing:
With Workbooks(x)
with:
With Workbooks(x & ".xlsx")
or
With Workbooks(x & ".xlsm")
EDIT#2:
If you are save as text, then try:
ActiveWorkbook.SaveAs Filename:="C:\Users\garys\Desktop\" & x & ".txt", FileFormat:=xlText, CreateBackup:=False
and refer like:
With Workbooks(x & ".txt")
来源:https://stackoverflow.com/questions/49907940/assigning-variable-workbook-name-with-inputbox-vba