Assigning variable workbook name with Inputbox VBA

戏子无情 提交于 2020-01-16 12:36:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!