conditionally auto name excel file using VBA

橙三吉。 提交于 2020-01-06 02:45:24

问题


I have following VB code that uses certain cell values (used to be fixed location) of a DB default file to name the current worksheet and save it in a specific folder with the use of an ActiveX button. However, column locations started varying in original file and VB ranges no longer pick the correct data to auto name the file. I created formulas (further below) to find the correct values I need to use to auto name the file. How do I insert those formulas in to my VB code for it to do job?

Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
Dim FileName2 As String
Dim FileName3 As String
Dim str As String, strLeft As String
str = Range("A7")
strLeft = Left(str, 9)
FileName1 = strLeft
FileName2 = RepCh(Range("B7").Value)
FileName3 = RepCh(Range("C7").Value)
Path = "…"
ActiveWorkbook.SaveAs FileName:=Path & FileName1 & "_" & FileName2 & "_" & FileName3 & "_" & ".xls", FileFormat:=xlCSV
End Sub

Formulae:

=LEFT(INDEX($A$7:$AZ$7,MATCH("Departure",$A$6:$AZ$6,0)), SEARCH("",INDEX($A$7:$AZ$7,MATCH("Departure",$A$6:$AZ$6,0)),9))

=INDEX($A$7:$AZ$7,MATCH("Vessel Name",$A$6:$AZ$6,0))

=INDEX($A$7:$AZ$7,MATCH("Voyage Number",$A$6:$AZ$6,0))

回答1:


There's more efficient ways than mine, but sometimes I just write formulas to a string variable, and save off the string variable.

However when you have " , then you need to split your formula into multiple strings and concatenate with & each time you have a quotation mark. (i.e - replace every " with Chr(34))

As an example for your top formula:

Dim vFormula1 As String
Dim vFormula2 As String
Dim vFormula3 As String

'Set up formula into string variable
vFormula1 = "=LEFT(INDEX($A$7:$AZ$7,MATCH(" & Chr(34) & "Departure" & Chr(34) & ",$A$6:$AZ$6,0)), SEARCH(" & Chr(34) & Chr(34) & ",INDEX($A$7:$AZ$7,MATCH(" & Chr(34) & "Departure" & Chr(34) & ",$A$6:$AZ$6,0)),9))"
vFormula2 = "=INDEX($A$7:$AZ$7,MATCH(" & Chr(34) & "Vessel Name" & Chr(34) & ",$A$6:$AZ$6,0))"
vFormula3 = "=INDEX($A$7:$AZ$7,MATCH(" & Chr(34) & "Voyage Number" & Chr(34) & ",$A$6:$AZ$6,0))"


'Then Put formula into a cell range
'Set sheet range here if needed
Range("A1") = vFormula1
Range("A2") = vFormula2
Range("A3") = vFormula3

'Then save code goes here
    'blah blah blah save files.


来源:https://stackoverflow.com/questions/35234154/conditionally-auto-name-excel-file-using-vba

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