我有以下VB代码,它使用数据库默认文件的某些单元格值(以前是固定位置)来命名当前工作表,并使用ActiveX按钮将其保存在特定文件夹中。但是,列位置在原始文件中开始变化,VB范围不再选择正确的数据来自动命名文件。我创建了公式(下面进一步),以找到我需要用来自动命名文件的正确值。如何将这些公式插入到我的VB代码中以便它完成工作?
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
公式:
=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))
答案 0 :(得分:1)
有比我更有效的方法,但有时我只是将公式写入字符串变量,并保存字符串变量。
但是,当您拥有"
时,您需要将公式拆分为多个字符串,并在每次使用引号时与&
连接。 (即 - 将每个"
替换为Chr(34)
)
作为您的顶级公式的示例:
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.